<?php

namespace app\api\controller;

use app\admin\model\Recharge;
use app\admin\model\shopro\Goods;
use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\White;
use think\Config;
use think\Db;
use \app\common\model\JwuserToken;
use \app\admin\model\share\ShareUser;
use \app\admin\model\share\Money as ShareMoney;
use \app\admin\model\share\Reward as ShareReward;
use \addons\shopro\model\Order;
use \addons\shopro\model\OrderItem;
use \app\common\library\Token;
use app\common\model\ShareConfig;
use app\common\model\Data;
use app\common\model\User;
use app\admin\model\share\Reward;
use \app\admin\model\share\CommonShare;
use addons\shopro\model\User as ShopUser;
use think\Validate;
use Carbon;

/**
 * 示例接口
 */
class Share extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['liveDate'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        // $token = $this->request->header('token');
        // if (empty($token)) {
        //     $this->error("token不能为空");
        // }
        // $user_token = (new JwuserToken())->where(['token'=>$token])->find();
        // if (empty($user_token)) {
        //     $this->error("请先登录");
        // } else {
        //     $this->user_id = $user_token['user_id'];
        // }
        $this->user_id = $this->auth->id;
    }

    /**
     * 注册绑定上下级关系
     */
    public function binding()
    {
        $parent_id = $this->request->post("parent_id"); // 邀请人ID
        $user = (new ShareUser())->add_share($parent_id, $this->user_id);//(['user_id'=>$this->user_id]);
        if ($user == 0) {
            $this->error("邀请码已满额");
        } else {
            $this->success('成功');
        }
    }

    //联创收益纪录
    public function lianc()
    {
        $date = $this->request->param("date",'','trim');
        $type = $this->request->param("type",'1','trim');

        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $srart = strtotime($starttime);
        $end = strtotime($endtime);
        $where = [];
        if($type == 1){
            $where['user_id'] = $this->auth->id;
            $lists = Db::name("share_goods_reward")
                ->where($where)
                ->whereBetween("addtime",[$srart,$end])
                ->order("addtime desc")
                ->paginate();
            $this->success("联创收益纪录",$lists);
        }else{
            $order_lists = Db::name("shopro_order o")
                ->field("g.creation_money as money,o.paytime as addtime")
                ->join("shopro_goods g","g.id = o.goods_id")
                ->where('o.status','>',0)
                ->where('g.creation_money','>',0)
                ->where(['o.share_retreat'=>0])
                ->whereBetween("o.paytime",[$srart,$end])
                ->order("o.paytime desc")
                ->paginate();
            $this->success("联创收益纪录",$order_lists);
        }


    }


    /**
     * 分销订单
     */
    public function order()
    {
        $order_id = $this->request->post("order_id"); //订单id
        $goods_id = $this->request->post("goods_id"); //商品ID
        $res = (new CommonShare())->add_share_order($order_id, $goods_id, $this->user_id);
        if ($res == 0) {
            $this->error("失败");
        } else {
            $this->success('成功');
        }
    }


    private function add_reward($type, $money, $order_id)
    {
        $reward = new ShareReward();
        $reward->money = $money;
        $reward->type = $type;
        $reward->order_id = $order_id;
        $reward->addtime = time();
        $reward->mutual_money = bcmul(0.1, $money, 2);
        $reward->save();
    }

    // type 1 直推 2极差 3日创收 4周创收
    private function add_money($type, $money, $order_id, $user_id, $role, $goods_id)
    {
        if (!empty($money) && $money != "0.00") {
//            $money = round($money);
//            if($money != 0){
            $ShareMoney = new ShareMoney();
            $ShareMoney->money = $money;
            $ShareMoney->mutual_money = bcmul(0.1, $money, 2);
            $ShareMoney->type = $type;
            $ShareMoney->order_id = $order_id;
            $ShareMoney->user_id = $user_id;
            $ShareMoney->goods_id = $goods_id;
            $ShareMoney->role = $role;
            $ShareMoney->addtime = time();
            $ShareMoney->save();
            $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
            $old_mutual_money = $user->mutual_money;
            $user->price += bcmul(0.9, $money, 2);
            $user->total_price += $money;
            $user->mutual_money += bcmul(0.1, $money, 2);
            $user->save();
            ShopUser::mutual(bcmul(0.1, $money, 2), $user_id, 'mutual_add', $order_id, '', [], $old_mutual_money);
//            }
        }
    }

    // 奖励级别 // "1":'推广员',"2":'代言人',"3":'一星网店经销商',"4":'二星网店经销商',"5":'银牌经销商',"6":'金牌经销商',"7":'钻石经销商'
    private function add_role($role)
    {
        $ShareConfig = ShareConfig::where(['goods_id' => 0, 'type' => 0, 'role' => $role])->find();
        if (empty($ShareConfig)) {
            $discount = 0;
        } else {
            $discount = $ShareConfig->proportion;
        }
        return $discount;
    }

    /**
     * order_id 订单id
     * user_id 用户id
     * role 上一级等级
     * pay_fee 支付金额
     */
    private function add_range($order_id, $user_id, $role, $pay_fee, $goods_id)
    {
        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        // 最高等级结束
        if ($user->role == 7) {
            if ($user->role == $role) {
                return 0;
            } else {
                $discount1 = $this->add_role($role);
                $discount2 = $this->add_role($user->role);
                $discount = bcsub($discount2, $discount1, 2);
                if ($discount <= 0) {
                    return 0;
                }
                $money = bcmul($discount, $pay_fee, 2);
                $this->add_money(2, $money, $order_id, $user->user_id, $user->role, $goods_id);
                return 0;
            }

        }
        // 同级下级不奖励
        if ($user->role <= $role) {
            return $this->add_range($order_id, $user->parent_id, $role, $pay_fee, $goods_id);
        } else {
            $discount1 = $this->add_role($role);
            $discount2 = $this->add_role($user->role);
            $discount = bcsub($discount2, $discount1, 2);
            $money = bcmul($discount, $pay_fee, 2);
            $this->add_money(2, $money, $order_id, $user->user_id, $user->role, $goods_id);
            return $this->add_range($order_id, $user->parent_id, $user->role, $pay_fee, $goods_id);
        }
    }

    private function promotion($user_id, $role)
    {
        $parent_user = (new ShareUser())->where(['parent_id' => $user_id])->select();
        if (count($parent_user) < 3) {
            return 0; // 本身 a
        } else {
            $temp_num = 0;
            foreach ($parent_user as $value) {
                $shareAll = (new ShareUser())->where(['is_delete' => 0])->select();
                # 获取所有的下级成员
                $sonShareAll = Data::channelList($shareAll, $value['user_id'], "", 'user_id', 'parent_id');
                if ($value['role'] == $role) {
                    $temp_num += 1;
                    continue;
                }
                foreach ($sonShareAll as $user1) {
                    if ($user1['role'] == $role) {
                        $temp_num += 1;
                        break;
                    }
                }
            }
            if ($temp_num == 3) {
                $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
                $user->role = bcadd($user->role, 1);
                $user->save();
            }
            return 0;
        }
    }

    /**
     * 用户信息
     */
    public function getuser()
    {
        $user = (new ShareUser())->get(['user_id' => $this->user_id]); // 分销用户
        if (!empty($user)) {
            $user['role_name'] = $this->get_role($user['role']);

            $user['role_name_future'] = $user['role_name'];

            if ($user['is_union'] == 1) {
                $user['role_name_future'] = $user['role_name_future'] . ',' . '联创伙伴';
            }


            if ($user['is_leader'] == 1) {
                $user['role_name_future'] = $user['role_name_future'] . ',' . '项目负责人';
            } elseif ($user['is_sep_income'] == 1) {
                $user['role_name_future'] = $user['role_name_future'] . ',' . '独立负责人';
            }

            $user1 = (new ShareUser())->get(['user_id' => $user->parent_id]); // 父级
            $user2 = (new ShareUser())->get(['user_id' => $user->inviter_id]); // 邀请人
            $user3 = (new User())->get(['id' => $user->parent_id]); // 父级
            $user4 = (new User())->get(['id' => $user->inviter_id]); // 邀请人
            $user['parent_role_name'] = $this->get_role($user1['role']);
            $user['inviter_role_name'] = $this->get_role($user2['role']);
            $user['parent_mobile'] = $user3['mobile'];
            $user['inviter_mobile'] = $user4['mobile'];
            $user['price'] = sprintf('%.2f', $user['price']);
            // $user['price'] = round($user['price']);
            $shareAll = (new ShareUser())->where(['is_delete' => 0])->select();
            # 获取所有的下级成员

            $top_id = \db("user")->where('mobile', '13131388888')->value('id');
            if ($this->user_id == $top_id) {
                $s = '%/' . $this->user_id;
            } else {
                $s = '%/' . $this->user_id . '/%';
            }

            if ($user['is_leader'] == 1) {
                $sonShareAll = (new ShareUser())->where('role_url', 'like', '%/' . $top_id)
                    ->where(['is_delete' => 0])
                    ->where('role > 0')
                    ->count();
                log_print((new ShareUser())->getLastSql(), $sonShareAll);
                $user['alluser'] = $sonShareAll + 1;
            } else {
                $sonShareAll = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0])
                    ->where('role > 0')
                    ->count();
                $user['alluser'] = $sonShareAll + 1;

                //校验用户数据 如果网体数据和数据库存储的不一致，则更新数据库
                if ($user['alluser'] != $user['amount']) {
                    \db("share_user")->where('user_id', $user['user_id'])->update([
                        'amount' => $user['alluser'],
                    ]);
                    $user['amount'] = $user['alluser'];
                }
            }


            $temp_role = (int)$user['role'] - 1;
            $user['subordinate'] = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0, 'role' => $temp_role])->count();
            //下级用户
            $low_user = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0])->select();
            $ids = "";
            foreach ($low_user as $k => $v) {
                $ids .= $v['user_id'] . ',';
            }
            $ids = trim($ids, ",");
            //当天
            $day = strtotime(date('Y-m-d', time()));
            if ($ids) {
                $inviter_list = Db::name("share_user")->where(['parent_id' => $this->user_id])->select();
                $low_one_list = [];
                $pattern = Db::name("config")->where(['name'=>'pattern'])->value('value');
                if(isset($pattern) && $pattern == 2){
                    $dj = ['无', '代言人', '创客', '网店店长', '网店店主', '一级经销商', '二级经销商', '三级经销商'];
                }elseif(isset($pattern) && $pattern == 3){
                    $dj = ['无', '推广员', '代言人', '一星网店', '二星网店', '一级代理商', '二级代理商', '三级代理商'];
                }else{
                    $dj = ['无', '推广员', '代言人', '一星网店经销商', '二星网店经销商', '银牌经销商', '金牌经销商', '钻石经销商'];
                }

                foreach ($inviter_list as $k1 => $v1) {
                    $low_user = (new ShareUser())->where('role_url', 'like', '%/' . $v1['user_id'] . '/%')->where(['is_delete' => 0])->select();
                    $low_ids = "";
                    foreach ($low_user as $k => $v) {
                        $low_ids .= $v['user_id'] . ',';
                    }
                    $low_ids = trim($low_ids, ",") . ',' . $v1['user_id'];

                    $low_or_where['user_id'] = ['in', $low_ids];
                    $low_or_where['status'] = ['in', '1,2'];
                    $low_or_where['one_day'] = ['in', '0,1,2,5'];
                    $low_or_where['createtime'] = ['>', $day];
                    $low_or_where['share_retreat'] = ['neq', 2];
                    $one_list_count = Db::name("shopro_order")
                        ->where($low_or_where)
                        ->count();
                    $u_data = Db::name("user")->where(['id' => $v1['user_id']])->find();
                    $low_one_list[$k1]['mobile'] = $u_data['mobile'];
                    $low_one_list[$k1]['role_name'] = $dj[$v1['role']];
                    $low_one_list[$k1]['order_sum'] = $one_list_count;

                    $hai_sum = 0;
                    $hai_user = (new ShareUser())->where('role_url', 'like', '%/' . $v1['user_id'] . '/%')->order('role desc')->find();
                    if (isset($hai_user)) {
                        $hai_sum = (new ShareUser())->where('role_url', 'like', '%/' . $v1['user_id'] . '/%')->where(['is_delete' => 0])->where(['role' => $hai_user['role']])->count();
                        if ($hai_user) {
                            $hai_u = Db::name("user")->where(['id' => $hai_user['user_id']])->find();
                            $low_one_list[$k1]['hai_mobile'] = $hai_u['mobile'];
                            // var_dump($hai_user);
                            $low_one_list[$k1]['hai_role_name'] = $dj[$hai_user['role']];
                        } else {
                            $hai_u = Db::name("user")->where(['id' => $v1['user_id']])->find();
                            $low_one_list[$k1]['hai_mobile'] = $hai_u['mobile'];
                        }
                        if ($v1['role'] > $hai_user['role']) {
                            $hai_sum = 1;
                            $hai_u = Db::name("user")->where(['id' => $v1['user_id']])->find();
                            $low_one_list[$k1]['hai_mobile'] = $hai_u['mobile'];
                            $low_one_list[$k1]['hai_role_name'] = $dj[$v1['role']];
                        }
                        if ($v1['role'] == $hai_user['role']) {
                            $hai_sum = $hai_sum + 1;
                        }
                    }

                    $low_one_list[$k1]['user_sum'] = $hai_sum == 0 ? 1 : $hai_sum;
                    $low_one_list[$k1]['user_id'] = $v1['user_id'];
                    $low_ids = '';
                }
                $or_where['user_id'] = ['in', $ids];

                $or_where['status'] = ['in', '1,2'];
                $or_where['one_day'] = ['in', '0,1,2,5'];
                $or_where['createtime'] = ['>', $day];
                $or_where['share_retreat'] = ['neq', 2];

                $one_sum = Db::name("shopro_order")
                    ->where($or_where)
                    ->sum("total_amount");

                $user['one_sum'] = round($one_sum, 2);
                $user['one_list'] = $low_one_list;
                //昨天
                $y_day = strtotime(date("Y-m-d", strtotime("-1 day")));
                $y_or_where['user_id'] = ['in', $ids];
                $y_or_where['status'] = ['in', '1,2'];
                $y_or_where['one_day'] = ['in', '0,1,2,5'];
                $y_or_where['share_retreat'] = ['neq', 2];
                $y_or_where['createtime'] = ['between', [$y_day, $day]];
                $y_one_sum = Db::name("shopro_order")->where($y_or_where)->sum("total_amount");
                $user['y_one_sum'] = round($y_one_sum, 2);
                //当月
                $m_day = strtotime(date('Y-m', time()));
                $m_or_where['user_id'] = ['in', $ids];
                $m_or_where['status'] = ['in', '1,2'];
                $m_or_where['one_day'] = ['in', '0,1,2,5'];
                $m_or_where['share_retreat'] = ['neq', 2];
                $m_or_where['createtime'] = ['>', $m_day];
                $m_one_sum = Db::name("shopro_order")->where($m_or_where)->sum("total_amount");
                $user['m_one_sum'] = round($m_one_sum, 2);
            } else {
                $user['one_list'] = [];
                $user['one_sum'] = 0;
                $user['m_one_sum'] = 0;
                $user['y_one_sum'] = 0;
            }
            $my_user_data = (new User())->get(['id' => $this->user_id]);
            //qi11.1 判断30天内是否购买每月一品
            $m_day = strtotime('-30 day');
            $r_where['user_id'] = $this->user_id;
            $r_where['createtime'] = ['>', $m_day];
            $r_where['one_day'] = 1;
            $r_where['status'] = ['in', '1,2'];
            $r_where['share_retreat'] = ['neq', 2];
            $r_data = Db::name("shopro_order")->where($r_where)->find();

            $user['one_day_order'] = 1;
            $c_data = Db::name("config")->where(['name' => 'withdraw_sta', 'value' => 1])->find();//中慧特殊配置
            $team_withdraw_status = Config::get('site.team_withdraw_status') ? Config::get('site.team_withdraw_status') : 1;
            if (1 == $team_withdraw_status && empty($r_data)) {
                $user['one_day_order'] = 0;
                if ($c_data && $user['is_order'] == 0) {//中慧新客户不限制
                    $user['one_day_order'] = 1;
                }
                if ($user['one_day_order'] == 0) {
                    //后台设置的用户不限制
                    $with_mobile = Db::name("config")->where(['name' => 'with_mobile'])->find();
                    if ($with_mobile && $with_mobile['value']) {
                        $str_status = strstr($with_mobile['value'], ",");
                        if ($str_status) {
                            $mobiles = explode(',', $with_mobile['value']);
                            if (in_array($my_user_data['mobile'], $mobiles)) {
                                $user['one_day_order'] = 1;
                            }
                        } else {
                            if ($my_user_data['mobile'] == $with_mobile['value']) {
                                $user['one_day_order'] = 1;
                            }
                        }

                    }
                }

            }
            if ($user['one_day_order'] == 0) {//注册30天内不用购买也能提现
                $c_data = Db::name("config")->where(['name' => 'reg_with_time'])->find();
                if (isset($c_data)) {
                    $reg_with_time = $c_data['value'];
                } else {
                    $reg_with_time = 30;
                }
                $cha_time = time() - $reg_with_time * 60 * 60 * 24;
                if ($cha_time > $this->auth->createtime) {
                    $user['one_day_order'] = 0;
                } else {
                    $user['one_day_order'] = 1;
                }
            }
            $user['score_exchange'] = 1;//是否可以积分转增
            $ws = Db::name("config")->where(['name' => 'score_exchange'])->find();
            if (!$ws || $ws['value'] == '') {
                $user['score_exchange'] = 0;
            } else {
                if ($ws['value'] != 1) {
                    $user['score_exchange'] = 0;
                }
            }

            $user['is_leader_up'] = 0;//判断是否申请过独立负责人
            $in_status = Db::name("leader_user")->where(['user_id' => $this->user_id])->where('status', 'in', '0,1')->find();
            if ($in_status) {
                $user['is_leader_up'] = 1;
            }
            //统计团队人数
            $sum_user_count = (new ShareUser())->teamUserCount($this->user_id);//总推荐人数
            $myTeamUserCount = (new ShareUser())->myTeamUserCount($this->user_id);//我的总分享人数
            //$share = Db::name("share_user")->where(['user_id' => $this->user_id])->find();//我的总分享人数
            $my_share = (new ShareUser())
                ->where(['inviter_id' => $this->user_id])
                ->where('role > 0')
                ->count();
            $user['sum_user_count'] = $sum_user_count;
            $user['team_count'] = $myTeamUserCount;
            $user['my_share'] = $my_share;//我的分享人数
            $user['mutual_money'] = number_format($user['mutual_money'],2);
            $user['nickname'] = $my_user_data['nickname'];//昵称
            $user['staff'] = $my_user_data['staff'];//账号类型:0=正常,1=特殊,2=测试
            $user['is_vip'] = ($my_user_data['vip_exp_time'] < time()) ? 0 : $my_user_data['is_vip'];//VIP:0=否,1=普通会员,2=升级版会员

            $user['vip_exp_time'] = $user['is_vip'] ? datetime($my_user_data['vip_exp_time'], "Y年m月d日") : null;//会员到期时间
            //最少提现金额
            $with_less_money = Db::name("config")->where(['name' => 'with_less_money'])->find();
            if($with_less_money){
                $user['with_less_money'] = $with_less_money['value'];
            }else{
                $user['with_less_money'] = 10;
            }

        }
        //转换金额
        if($user['price'] >1000){
            $user['price_show'] = round($user['price']/10000,2)."万";
        }else{
            $user['price_show'] = $user['price'];
        }
        if($user['lp_price'] >1000){
            $user['lp_price_show'] = round($user['lp_price']/10000,2)."万";
        }else{
            $user['lp_price_show'] = $user['lp_price'];
        }
        if($user['advert_price'] >1000){
            $user['advert_price_show'] = round($user['advert_price']/10000,2)."万";
        }else{
            $user['advert_price_show'] = $user['advert_price'];
        }
        $mutual_money = str_replace(',','', $user['mutual_money']);
        if($mutual_money >1000){
            $user['mutual_money_show'] = round($mutual_money/10000,2)."万";
        }else{
            $user['mutual_money_show'] = $mutual_money;
        }
        if($user['old_price'] >1000){
            $user['old_price_show'] = round($user['old_price']/10000,2)."万";
        }else{
            $user['old_price_show'] = $user['old_price'];
        }
        $return_switch = Db::name("config")->where(['name' => 'return_switch'])->value("value");
        $user['return_switch'] = $return_switch??1;
        $creation_switch = Db::name("config")->where(['name' => 'creation_switch'])->value("value");
        $user['creation_switch'] = $creation_switch??1;
        $score_switch = Db::name("config")->where(['name' => 'score_switch'])->value("value");
        $user['score_switch'] = $score_switch??1;
        $pattern = Db::name("config")->where(['name'=>'pattern'])->value('value');
        if(isset($pattern) && $pattern > 1){
            $user['pattern'] = $pattern;
        }else{
            $user['pattern'] = 1;
        }
        $kf_img = Db::name("config")->where(['name' => 'kf_img'])->value("value");
        $user['kf_img'] = $kf_img?'https://oss.bigchun.com/'.$kf_img:'';
        $reg_switch = Db::name("config")->where(['name' => 'reg_switch'])->value("value");
        $user['reg_switch'] = $reg_switch??1;
        $old_transfer = Db::name("config")->where(['name' => 'old_transfer'])->value("value");
        $user['old_transfer'] = $old_transfer??1;
        $payment_type = Db::name("config")->where(['name' => 'payment_type'])->value("value");
        $user['payment_type'] = $payment_type??1;
        $pay_url = Db::name("config")->where(['name' => 'pay_url'])->value("value");
        $user['pay_url'] = $pay_url;
        $this->success('成功', $user);
    }

    /**
     * 网体 我的市场
     */

    public function FunctionName()
    {
        # code...
    }

    private function get_role($role)
    {
        $pattern = Db::name("config")->where(['name'=>'pattern'])->value('value');
        if(isset($pattern) && $pattern == 2){
            switch ($role) {
                case 1:
                    $role_name = '代言人';
                    break;
                case 2:
                    $role_name = '创客';
                    break;
                case 3:
                    $role_name = '网店店长';
                    break;
                case 4:
                    $role_name = '网店店主';
                    break;
                case 5:
                    $role_name = '一级经销商';
                    break;
                case 6:
                    $role_name = '二级经销商';
                    break;
                case 7:
                    $role_name = '三级经销商';
                    break;
                default:
                    $role_name = '无';
                    break;
            }
        }elseif(isset($pattern) && $pattern == 3){
            switch ($role) {
                case 1:
                    $role_name = '推广员';
                    break;
                case 2:
                    $role_name = '代言人';
                    break;
                case 3:
                    $role_name = '一星网店';
                    break;
                case 4:
                    $role_name = '二星网店';
                    break;
                case 5:
                    $role_name = '一级代理商';
                    break;
                case 6:
                    $role_name = '二级代理商';
                    break;
                case 7:
                    $role_name = '三级代理商';
                    break;
                default:
                    $role_name = '无';
                    break;
            }
        }else{
        switch ($role) {
            case 1:
                $role_name = '推广员';
                break;
            case 2:
                $role_name = '代言人';
                break;
            case 3:
                $role_name = '一星网店';
                break;
            case 4:
                $role_name = '二星网店';
                break;
            case 5:
                $role_name = '银牌';
                break;
            case 6:
                $role_name = '金牌';
                break;
            case 7:
                $role_name = '钻石';
                break;
            default:
                $role_name = '无';
                break;
        }
    }

        return $role_name;
    }

    /**
     * 3 个部门
     */
    public function get_department()
    {
        $status = $this->request->post("status") ?? 1; // 状态
        $offset = $this->request->post("offset"); // 第几页
        $offset = empty($offset) ? 0 : bcsub($offset, 1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 10 : $limit;
        $page = bcmul($offset, $limit);
        $pag_limit = bcadd($offset, 1) * $limit;
        $user = (new ShareUser())->get(['parent_id' => $this->user_id, 'role_type' => $status]); // 分销用户
        if (empty($user)) {
            $this->success('成功', array());
        }
        //$shareAll = (new ShareUser())->where(['is_delete'=>0])->select();
        # 获取所有的下级成员
        //$sonShareAll = Data::channelList($shareAll, $user->user_id, "", 'user_id', 'parent_id');
        $temp_data = array();
        $user1 = (new User())->get(['id' => $user->user_id]);
        if (!empty($user1) && $offset == 0) {
            $temp_data[] = array(
                'addtime' => date('Y-m-d H:i:s', $user['addtime']),
                'mobile' => $user1['mobile'],
                'role_name' => $this->get_role($user['role']),
            );
            $limit = $limit - 1;
        } else {
            $page = $page - 1;
        }

        if ($pag_limit - 1 == 0) {
            $this->success('成功', $temp_data);
        }

        $top_id = \db("user")->where('mobile', '13131388888')->value('id');
        if ($this->user_id == $top_id) {
            $s = '%/' . $this->user_id;
        } else {
            $s = '%/' . $this->user_id . '/%';
        }

        $sonShareAll = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0])->limit($page, $limit)->select();
        foreach ($sonShareAll as $key => $value) {
            $t_user = (new User())->get(['id' => $value['user_id']]);
            $temp_data[] = array(
                'addtime' => date('Y-m-d H:i:s', $value['addtime']),
                'mobile' => $t_user['mobile'],
                'role_name' => $this->get_role($value['role']),
            );
        }

        $this->success('成功', $temp_data);
    }

    /**
     * 获取业务经理
     */
    public function get_depar_list()
    {
        $user = (new ShareUser())->get(['user_id' => $this->user_id]); // 分销用户
        //$shareAll = (new ShareUser())->where(['is_delete'=>0])->select();
        # 获取所有的下级成员
        //$sonShareAll = Data::channelList($shareAll, $this->user_id, "", 'user_id', 'parent_id');

        $top_id = \db("user")->where('mobile', '13131388888')->value('id');
        if ($this->user_id == $top_id) {
            $s = '%/' . $this->user_id;
        } else {
            $s = '%/' . $this->user_id . '/%';
        }
        $temp_role = (int)$user['role'] - 1;
        $sonShareAll = (new ShareUser())->where('role_url', 'like', $s)->where(['is_delete' => 0, 'role' => $temp_role])->select();

        $temp_arr = array();
        foreach ($sonShareAll as $key => $value) {
            //if($value['role'] == $temp_role){
            $t_user = (new User())->get(['id' => $value['user_id']]);
            $temp_arr[] = array(
                'addtime' => date('Y-m-d H:i:s', $value['addtime']),
                'mobile' => $t_user['mobile'],
                'role_name' => $this->get_role($value['role']),
            );
            //}
        }
        $this->success('成功', $temp_arr);
    }

    /**
     * 统计
     */
    public function statistics()
    {
        $user = (new ShareUser())->get(['user_id' => $this->user_id]); // 分销用户
        $data = array();
        //开始时间
        $end_time = date('Y-m-d 00:00:00');
        // 本周周一时间
        $week_time1 = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
        // 当前时间
        $dq_time = date('Y-m-d H:i:s');
        $data['d_reward5'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 5, 'status' => 0])->sum('money');
        $data['d_reward4'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 4, 'status' => 0])->sum('money');
        $data['d_reward2'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 2, 'status' => 0])->sum('money');
        $data['d_reward1'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 1, 'status' => 0])->sum('money');
        $data['d_reward3'] = (new Reward())->where('addtime', 'between time', [$week_time1, $dq_time])->where(['type' => 3, 'status' => 0])->sum('money');
        $ShareUser1 = (new ShareUser())->where(['is_delete' => 0, 'role' => 1])->count();
        $ShareUser2 = (new ShareUser())->where(['is_delete' => 0, 'role' => 2])->count();
        $ShareUser3 = (new ShareUser())->where(['is_delete' => 0, 'role' => 3])->count();
        $ShareUser4 = (new ShareUser())->where(['is_delete' => 0, 'role' => 4])->count();
        $temp_arr = array();
        $temp_arr[] = array('role' => 1, 'name' => '推广员日创收', 'money' => $data['d_reward1'], 'count' => $ShareUser1);
        $temp_arr[] = array('role' => 2, 'name' => '代言人日创收', 'money' => $data['d_reward2'], 'count' => $ShareUser2);
        $temp_arr[] = array('role' => 3, 'name' => '一星网店主日创收', 'money' => $data['d_reward4'], 'count' => $ShareUser3);
        $temp_arr[] = array('role' => 4, 'name' => '二星网店主日创收', 'money' => $data['d_reward5'], 'count' => $ShareUser4);
        if ($user->role == 3) {
            $temp_week_arr = array('role' => 5, 'name' => '一星网店主周创收', 'money' => $data['d_reward1']);
        } else {
            $temp_week_arr = array();
        }

        $this->success('成功', array('lists' => $temp_arr, 'week_reward' => $temp_week_arr));
    }

    /**
     *
     */
    public function getmoney()
    {
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $srart = strtotime($starttime);
        $end = strtotime($endtime);
        $is_old = $this->request->post("is_old", 0);//0新资金1老资金2零售收益
        $offset = $this->request->post("offset", 1); // 第几页
        $limit = 10;
        $user_money_log = db('user_money_log')
            ->where('user_id', $this->user_id)
            ->where(['is_old' => $is_old])
            ->whereBetween("createtime",[$srart,$end])
            ->field('id,before,after,money,type,createtime as addtime,memo as type_name,mobile,order_sn,user_id,order_id')
            ->limit(($offset-1)*$limit,$limit)
            ->order('addtime desc')
            ->select();
        foreach ($user_money_log as $k => $v) {
            if ($v['before'] >= $v['after']) {
                $user_money_log[$k]['money'] = abs($v['money']);
                $user_money_log[$k]['flag'] = '-';
            } else {
                $user_money_log[$k]['flag'] = '+';
            }
            $user_money_log[$k]['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
            switch ($v['type']) {
                case 1:
                    $user_money_log[$k]['type_name'] = '管理员变更金额';
                    break;
                case 2:
                    $user_money_log[$k]['goods_title'] = "";
                    if(!empty($v['order_sn'])||!empty($v['order_id'])){
                        //增加购买商品
                        //商品信息
                        $order = Order::where(['order_sn'=>$v['order_sn']])->whereOr("id",$v['order_id'])->find();
                        if($order){
                            $goods = Goods::where(['id'=>$order->goods_id])->find();
                            if($goods){
                                $user_money_log[$k]['goods_title'] = $goods->title;
                                $user_money_log[$k]['goodsid'] = $goods->id;
                            }
                        }
                    }
                    if ($user_money_log[$k]['flag'] == '+') {
                        $user_money_log[$k]['type_name'] = '商品退单';
                        break;
                    } else {

                        $user_money_log[$k]['type_name'] = '购买商品';
                        break;
                    }

                case 3:
                    if ($user_money_log[$k]['flag'] == '+') {
                        $user_money_log[$k]['type_name'] = '派发佣金';
                        break;
                    } else {
                        $user_money_log[$k]['type_name'] = '扣除佣金';
                        break;
                    }

                case 4:
                    $user_money_log[$k]['type_name'] = '余额充值';
                    break;
                case 5:
                    $user_money_log[$k]['type_name'] = '兑换提货卷';
                    break;
                case 6:
                    //$user_money_log[$k]['type_name'] = '提现';
                    if ($user_money_log[$k]['flag'] == '+') {
                        $user_money_log[$k]['type_name'] = '提现驳回';
                        break;
                    } else {
                        $user_money_log[$k]['type_name'] = '提现';
                        break;
                    }
                case 7:
                    $user_money_log[$k]['type_name'] = '余额转赠';
                    if ($user_money_log[$k]['flag'] == '+') {
                        //增加 余额转让   来自131****8888      2022-10-26 18:45:26       +10
                        $user = Db::name("user")->where(['mobile' => $v['mobile']])->find();
                        if($user){
                            $user_money_log[$k]['username'] = $user["username"];
                        }
                    }elseif ($user_money_log[$k]['flag']=="-"){
                        //增加 余额转让   转给131****8888      2022-10-26 18:45:26       -10
                        $user = Db::name("user")->where(['mobile' => $v['mobile']])->find();
                        if($user){
                            $user_money_log[$k]['username'] = $user["username"];
                        }
                    }
                    break;
                case 8:
                    $user_money_log[$k]['type_name'] = '充值余额';
                    //查询支付类型
                    $paytype = Recharge::where(['order_sn'=>$v['order_sn']])->whereOr("id",$v['order_id'])->value("pay_type");//支付类型
                    if($paytype=="wechat"){
                        $pay_type_text = "微信";
                    }else{
                        $pay_type_text = "支付宝";
                    }
                    $user_money_log[$k]['pay_type_text'] = $pay_type_text;
                    break;
                case 9:
                    if ($user_money_log[$k]['flag'] == '+') {
                        $user_money_log[$k]['type_name'] = '申请联创不通过';
                        break;
                    } else {
                        $user_money_log[$k]['type_name'] = '申请联创';
                        break;
                    }
                    break;
                case 10:
                    $user_money_log[$k]['type_name'] = '零售收益';
                    //增加-零售收益：VIKK V16 PLUS      来自131****8888      2022-10-26 18:45:26      +236.26
                    //用户信息
                    $user  =Db::name("user")->where(['id' => $v['user_id']])->find();
                    if($user){
                        $user_money_log[$k]['username'] = $user["username"];
                    }
                    //商品信息
                    $order = Order::where(['id'=>$v['order_id']])->whereOr("order_sn",$v['order_sn'])->find();
                    if($order){
                        $goods = Goods::where(['id'=>$order->goods_id])->find();
                        if($goods){
                            $user_money_log[$k]['goods_title'] = $goods->title;
                            $user_money_log[$k]['goodsid'] = $goods->id;
                        }
                    }
                    break;
                case 11:
                    $user_money_log[$k]['type_name'] = '批发收益';
                    //增加-批发收益：VIKK V16 PLUS      来自131****8888      2022-10-26 18:45:26      +236.26
                    //用户信息
                    $user  =Db::name("user")->where(['id' => $v['user_id']])->find();
                    if($user){
                        $user_money_log[$k]['username'] = $user["username"];
                    }
                    //商品信息
                    $order = Order::where(['id'=>$v['order_id']])->whereOr("order_sn",$v['order_sn'])->find();
                    if($order){
                        $goods = Goods::where(['id'=>$order->goods_id])->find();
                        if($goods){
                            $user_money_log[$k]['goods_title'] = $goods->title;
                            $user_money_log[$k]['goodsid'] = $goods->id;
                        }
                    }
                    break;
                case 12:
                    $user_money_log[$k]['type_name'] = '退货退回收益';
                    //查询支付类型
                    $paytype = Recharge::where(['order_sn'=>$v['order_sn']])->value("pay_type");//支付类型
                    if($paytype=="wechat"){
                        $pay_type_text = "微信";
                    }else{
                        $pay_type_text = "支付宝";
                    }
                    $user_money_log[$k]['pay_type_text'] = $pay_type_text;
                    break;
                case 13:
                    $user_money_log[$k]['type_name'] = '全部余额兑换股票权益（可联系负责人）';
                    break;
            }
            unset($user_money_log[$k]['before']);
            unset($user_money_log[$k]['after']);
            // unset($user_money_log[$k]['type']);
        }
        $this->success('成功', $user_money_log);
    }

    //   新增
    public function sale_info()
    {
        $user_id = $this->auth->id;
        $role = DB::name('share_user')->where('user_id', $user_id)->value('role');
        $model = new ShareMoney();
        // 今日
        $to_time = strtotime(date('Y-m-d'));
        $ye_time = strtotime(date('Y-m-d')) - 86400;
        $today_money = $model->where('user_id', $user_id)->where('addtime > ' . $to_time)->whereIn('type', [1, 2])->sum('money');
        $yestday_money = $model->where('user_id', $user_id)->where('addtime < ' . $to_time . '  and addtime > ' . $ye_time)->whereIn('type', [1, 2])->sum('money');
        $total_money = $model->where('user_id', $user_id)->whereIn('type', [1, 2])->sum('money');
        $this->success('成功', compact('today_money', 'yestday_money', 'total_money'));
    }

    public function sale_list()
    {
        $user_id = $this->auth->id;
        $model = new ShareMoney();
        $list = $model::with('goods')->where('user_id', $user_id)->paginate(20);
        foreach ($list as $row) {
            $row->getRelation('goods')->visible(['title']);
        }
        $this->success('成功', $list);
    }

    public function user_list()
    {
        $user_id = $this->auth->id;
        $model = new ShareUser();
        $list = $model::with('user')->where('inviter_id', $user_id)->order('id', 'desc')->paginate(20);
        foreach ($list as $row) {
            $row->visible(['id', 'user_id', 'name', 'role', 'addtime', 'user']);
            $row->getRelation('user')->visible(['nickname', 'mobile']);
            $row->user->mobile = preg_match("/^1[3-9]{1}\d{9}$/", $row->user->mobile) ? substr_replace($row->user->mobile, '****', 3, 4) : $row->user->mobile;
        }
        $this->success('成功', $list);
    }


    //   新增
    public function day_info()
    {
        $user_id = $this->auth->id;
        // $role =  DB::name('share_user')->where('user_id',$user_id)->value('role');
        $model = new ShareMoney();
        $end_time = strtotime(date('Y-m-d'));
        $ShareReward5 = (new ShareReward())->where('addtime  > ' . $end_time)->where(['type' => 5, 'status' => 0])->sum('money');
        $ShareReward4 = (new ShareReward())->where('addtime  > ' . $end_time)->where(['type' => 4, 'status' => 0])->sum('money');
        $ShareReward2 = (new ShareReward())->where('addtime  > ' . $end_time)->where(['type' => 2, 'status' => 0])->sum('money');
        $ShareReward1 = (new ShareReward())->where('addtime  > ' . $end_time)->where(['type' => 1, 'status' => 0])->sum('money');
        $ShareUser1 = (new ShareUser())->where(['is_delete' => 0, 'role' => 1])->select();
        $ShareUser2 = (new ShareUser())->where(['is_delete' => 0, 'role' => 2])->select();
        $ShareUser3 = (new ShareUser())->where(['is_delete' => 0, 'role' => 3])->select();
        $ShareUser4 = (new ShareUser())->where(['is_delete' => 0, 'role' => 4])->select();
        $money1 = empty(count($ShareUser1)) ? 0 : bcdiv($ShareReward1, count($ShareUser1), 2);
        $money2 = empty(count($ShareUser2)) ? 0 : bcdiv($ShareReward2, count($ShareUser2), 2);
        $money4 = empty(count($ShareUser3)) ? 0 : bcdiv($ShareReward4, count($ShareUser3), 2);
        $money5 = empty(count($ShareUser4)) ? 0 : bcdiv($ShareReward5, count($ShareUser4), 2);
        $total_money = $money1 + $money2 + $money4 + $money5;
        $to_time = strtotime(date('Y-m-d'));
        $ye_time = strtotime(date('Y-m-d')) - 86400;
        $data = [];
        for ($role = 1; $role <= 4; $role++) {
            if ($role < 3) {
                // 今日
                $today_money = $model->where('user_id', $user_id)->where('role', $role)->where('addtime > ' . $to_time)->where('type', 3)->sum('money');
                $yestday_money = $model->where('user_id', $user_id)->where('role', $role)->where('addtime < ' . $to_time . '  and addtime > ' . $ye_time)->where('type', 3)->sum('money');
                if ($role == 1) {
                    $on_money = $money1;
                } else {
                    $on_money = $money2;
                }
                $data[] = [
                    'role' => $role,
                    'list' => [
                        'today_money' => $today_money,
                        'yestday_money' => $yestday_money,
                        'on_money' => $on_money
                    ]
                ];
            } else {
                $week_time = strtotime(date("Y-m-d", strtotime("-7 day")));
                $ShareReward3 = (new ShareReward())->where('addtime > ' . $week_time)->where(['type' => 3, 'status' => 0])->sum('money');
                $on_week_money = empty(count($ShareUser3)) ? 0 : bcdiv($ShareReward3, count($ShareUser3), 2);

                $today_money = $model->where('user_id', $user_id)->where('role', $role)->where('addtime > ' . $to_time)->where('type', 3)->sum('money');
                $yestday_money = $model->where('user_id', $user_id)->where('role', $role)->where('addtime < ' . $to_time . '  and addtime > ' . $ye_time)->where('type', 3)->sum('money');
                $w = date('w') > 0 ? date('w') : 7;
                $to_week = strtotime(date('Y-m-d')) - ($w - 1) * 86400;
                $ye_week = strtotime(date('Y-m-d')) - ($w - 1) * 86400 - 7 * 86400;
                $week_money = $model->where('user_id', $user_id)->where('addtime > ' . $to_week)->where('role', $role)->where('type', 4)->sum('money');
                if ($role == 3) {
                    $on_money = $money4;
                } else {
                    $on_money = $money5;
                }
                $data[] = [
                    'role' => $role,
                    'list' => [
                        'today_money' => $today_money,
                        'yestday_money' => $yestday_money,
                        'on_money' => $on_money,
                        'week_money' => $week_money,
                        'on_week_money' => $on_week_money,
                    ]
                ];
            }
        }
        $yestday_money = $model->where('user_id', $user_id)->where('role', $role)->where('addtime < ' . $to_time . '  and addtime > ' . $ye_time)->where('type', 3)->sum('money');
        $all__money = $model->where('user_id', $user_id)->whereIn('type', [3, 4])->sum('money');
        $data[] = [
            'role' => 'total',
            'list' => [
                'yestday_money' => $yestday_money,
                'on_money' => $total_money,
                'total_money' => $all__money,
            ]
        ];
        $this->success('ok', $data);

    }


    private function get_type($role)
    {
        switch ($role) {
            case 1:
                $role_name = '零售收益';
                break;
            case 2:
                $role_name = '批发收益';
                break;
            case 3:
                $role_name = '日广告收益';
                //增加身份等级

                break;
            case 4:
                $role_name = '周广告收益';
                break;
            default:
                $role_name = '无';
                break;
        }
        return $role_name;
    }

    public function direct_lists()
    {
        $offset = $this->request->post("offset"); // 第几页
        $offset = empty($offset) ? 0 : bcsub($offset, 1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 10 : $limit;
        $this->set_page($offset, $limit);
        $list = (new ShareUser())
            ->with('user')
            ->where(['inviter_id' => $this->user_id])
            ->order('addtime', 'DESC')
            ->where('role > 0')
            ->paginate($limit);
        foreach ($list as $key => &$row) {
            $row['role'] = $this->get_role($row['role']);
            $row->visible(['id', 'user_id', 'role', 'addtime', 'parent_id', 'inviter_id', 'price', 'total_price', 'user.nickname', 'user.mobile', 'user.invitecode', 'user.createtime', 'score']);
        }
        //统计团队人数
        $sum_user_count = (new ShareUser())->teamUserCount($this->user_id);//总推荐人数
        $share = Db::name("share_user")->where(['user_id' => $this->user_id])->find();
        $result = array("total" => $list->total(), 'sum_user_count' => $sum_user_count, "team_count" => $share['amount'], 'is_sep_income' => $share['is_sep_income'], "rows" => $list->items());

        $this->success('成功', $result);
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 批发零售收益
     */
    public function profit_statistics()
    {
        $type = $this->request->post("type", 1);// 1零售 2批发
        $user = (new ShareUser())->get(['user_id' => $this->user_id]); // 分销用户
        if (!$user) $this->error('用户不存在');

        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $start = strtotime($starttime);
        $end = strtotime($endtime);

        //当天
        $day = strtotime(date('Y-m-d', time()));
        //昨天
        $y_day = strtotime(date("Y-m-d", strtotime("-1 day")));

        $list = Db::name('share_money')
            ->where('user_id', $this->user_id)
            ->whereBetween("addtime",[$start,$end])
            ->where('type', $type)
            ->order('id desc')
            ->select();

        $one_sum = \db("share_money")
            ->where('user_id', $this->user_id)
            ->where('type', $type)
//            ->where('status', 0)
            ->sum("money+mutual_money");

        $one_m_sum = \db("share_money")
            ->where('user_id', $this->user_id)
            ->where('type', $type)
            ->where('addtime', 'gt', $day)
            ->sum("money+mutual_money");

        $order_ids = array_column($list, 'order_id');
        $orders = \db("shopro_order o")->where('o.id', 'in', $order_ids)
            ->join("shopro_goods g", 'g.id = o.goods_id')
            ->field('o.id,g.title')->select();
        $order_goods = [];
        foreach ($orders as $v) {
            $order_goods[$v['id']] = $v['title'];
        }

        $y_all_sum = \db("shopro_order")->where('id', 'in', $order_ids)
            ->where('createtime', 'lt', $day)
            ->where('createtime', 'gt', $y_day)
            ->sum("pay_fee");

        $all_sum = \db("shopro_order")->where('id', 'in', $order_ids)
            ->where('createtime', 'gt', $day)
            ->sum("pay_fee");
        $money_log = Db::name('user_money_log')
            ->where('user_id', $this->user_id)
            ->where('type', $type)
            ->order('id desc')
            ->select();
        foreach ($list as &$v) {
            $v['addtime'] = date("Y-m-d H:i", $v['addtime']);
            //$v['createtime'] = date("Y-m-d H:i", $v['createtime']);
            $v['money'] = number_format(($v['money'] + $v['mutual_money']), 2);
            $v['goods_title'] = isset($order_goods[$v['order_id']]) ? $order_goods[$v['order_id']] : '';
            //增加用户手机号码
            $v['user_mobile'] = \addons\shopro\model\User::where(['id'=>$this->user_id])->value("mobile")??'';
            $order_data = Db::name("shopro_order")->where(['id'=>$v['order_id']])->find();
            $formUser = User::where(["id"=>$order_data['user_id']])->find();  //来源用户信息
            $v['form_usermobile'] = isset($formUser->mobile)?substr_replace($formUser->username,'****',3,4):'';
            /* $order_data = Db::name("shopro_order")->where(['id'=>$v['order_id']])->find();
             $user_data = Db::name("user")->where(['id'=>$order_data['user_id']])->find();
             if($v['after'] > $v['before']){
                 $fh = '+';
                 $zt = '来自：';
             }else{
                 $v['money'] = abs($v['money']);
                 $fh = '-';
                 $zt = '转给：';
             }
             $v['money'] = $fh.$v['money'];
             $v['money_source'] =  $zt.$user_data['boile'];*/

        }

        $usersh['one_list'] = $list;
        $usersh['one_sum'] = number_format($one_sum, 2);
        $usersh['m_one_sum'] = number_format($one_m_sum, 2);
        $usersh['all_sum'] = $all_sum;
        $usersh['y_all_sum'] = $y_all_sum;

        $this->success('成功', $usersh);
    }


    /**
     * 新接口:我的零售收益纪录
     */
    /*
     *  public function myRetailLog()
    {
        //默认零售收益
        $type = $this->request->param("type",10,'intval');
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $start = strtotime($starttime);
        $end = strtotime($endtime);
        $list = Db::name('user_money_log')
            ->where('user_id', $this->user_id)
            ->where('type', "=",$type)
            ->whereBetween("createtime",[$start,$end])
            ->order('id desc')
            ->paginate();
        if($list){
            $data = $list->toArray();
            foreach ($data['data'] as $k=>&$v){
                $v['title'] = " 联创收益";
                $v['goods_title'] = "";
                $v['username'] = "";
                $v['form_username'] = "";
                if (isset($v['user_id'])){
                    $user = User::where(['id'=>$v['user_id']])->find();
                    if($user){
                        $v['username'] = $user->username;
                    }
                }
                if(isset($v['order_id'])){
                    $order = Order::where(['id'=>$v['order_id']])->find();
                    if($order){
                        $user = User::where(['id'=>$v['user_id']])->find();
                        $v['form_username'] = "来自于".$user->username;
                        $v['form_mobile'] =$order->phone;
                        $goods = Goods::where(['id'=>$order->goods_id])->find();
                        if($goods){
                            $v['goods_title'] = $goods->title;

                        }
                    }
                }
                if ($v['before'] >= $v['after']) {
                    $v['money'] = abs($v['money']);
                    $v['flag'] = '-';
                    $v['goods_title'] = '退回-'.$v['goods_title'];
                } else {
                    $v['flag'] = '+';
                    $v['goods_title'] = '增加-'.$v['goods_title'];
                }
            }
        }
        $this->success("我的零售收益纪录",$data);
    }
     */
    public function myRetailLog()
    {
        //默认零售收益
        $type = $this->request->param("type",10,'intval');//10零售11批发
        if($type == 10){
            $type = 1;
        }else{
            $type = 2;
        }
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $start = strtotime($starttime);
        $end = strtotime($endtime);
        $list = Db::name('share_money')
            ->where('user_id', $this->user_id)
            ->where('type', "=",$type)
            ->whereBetween("addtime",[$start,$end])
            ->order('id desc')
            ->paginate();
        if($list){
            $data = $list->toArray();
            foreach ($data['data'] as $k=>&$v){
                $v['title'] = " 联创收益";
                $v['goods_title'] = "";
                $v['username'] = "";
                $v['form_username'] = "";
                $v['money'] = $v['money']+$v['mutual_money'];
                if (isset($v['user_id'])){
                    $user = User::where(['id'=>$v['user_id']])->find();
                    if($user){
                        $v['username'] = $user->username;
                    }
                }
                if(isset($v['order_id'])){
                    $order = Order::where(['id'=>$v['order_id']])->find();
                    if($order){
                        $user = User::where(['id'=>$v['user_id']])->find();
                        $v['form_username'] = "来自于".$user->username;
                        $v['form_mobile'] =$order->phone;
                        $goods = Goods::where(['id'=>$order->goods_id])->find();
                        if($goods){
                            $v['goods_title'] = $goods->title;

                        }
                    }
                }
                $v['flag'] = '+';
                $v['goods_title'] = '增加-'.$v['goods_title'];
            }
        }
        $this->success("我的零售收益纪录",$data);
    }

    /**
     * 广告收益明细
     */
    public function advertising_earnings_record()
    {
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $start = strtotime($starttime);
        $end = strtotime($endtime);
        //已发放的广告收益明细(总额)
        $total = ShareMoney::where("type",">",2)->whereBetween("addtime",[$start,$end])->sum("money");
        //我的已发放的广告收益明细(总额)
        $myTotal = ShareMoney::where(['user_id'=>$this->auth->id])->where("type",">",2)->whereBetween("addtime",[$start,$end])->sum("money");
        //我的广告纪录

        $advertisingList = ShareMoney::where(['user_id'=>$this->auth->id])->where("type",">",2)->whereBetween("addtime",[$start,$end])->paginate()->each(function($item){
            $item['addtime'] = date("Y-m-d H:i:s",$item['addtime']);
            $typeArr = [
                '3' =>  "日广告收益",
                '4' =>  "周广告收益",
                '5' =>  "多商户进货成本",
                '6' =>  "多商户一星网点分佣",
            ];
            $item['type_text'] = $typeArr[$item['type']];
        });
        $this->success("广告收益纪录",['total'=>$total,'mytotal'=>$myTotal,'list'=>$advertisingList]);

    }

    /**
     * 广告收益
     */
    public function advertising_revenue()
    {
        $user = (new ShareUser())->get(['user_id' => $this->user_id]); // 分销用户
        $user_flags = \db("share_user_flags")->where('user_id', $this->user_id)->find();
        $userWhere = [];
        $flags = '';
        if ($user_flags) {
            $userWhere['user_flags'] = $user_flags['user_flags'];
            $flags = $user_flags['user_flags'];
        } else {
            $userWhere['user_flags'] = '';
        }

        $data = array();
        //开始时间
        $end_time = date('Y-m-d 00:00:00');
        // 当前时间
        $dq_time = date('Y-m-d H:i:s');
        // 本周周一时间
        $week_time1 = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
        $sdefaultDate = date("Y-m-d");
        $first = 1;
        $w = date('w', strtotime($sdefaultDate));
        $week_start = date('Y-m-d H:i:s', strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days'));
        $data['d_reward5'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 5])->where($userWhere)->sum('money');
        $data['d_reward4'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 4])->where($userWhere)->sum('money');
        $data['d_reward3'] = (new Reward())->where('addtime', 'between time', [$week_start, $dq_time])->where(['type' => 3])->where($userWhere)->sum('money');
        $data['d_reward2'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 2])->where($userWhere)->sum('money');

        $data['d_reward1'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 1])->where($userWhere)->sum('money');
//        \think\Log::error(json_encode($data));

        //开始时间
        $yest_time = date("Y-m-d", strtotime("-1 day"));
        // 上周一时间
        //$week_time = date('Y-m-d H:i:s', mktime(0,0,0,date('m'),date('d')-date('w')+1-14,date('Y')));
        $week_time = date('Y-m-d H:i:s', mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 14, date('Y')));
        //echo $week_time;
        $ShareReward5 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 5])->where($userWhere)->sum('money');
        $ShareReward4 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 4])->where($userWhere)->sum('money');
        $ShareReward3 = (new ShareReward())->where('addtime', 'between time', [$week_time, $week_start])->where(['type' => 3])->where($userWhere)->sum('money');
        $ShareReward2 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 2])->where($userWhere)->sum('money');
        $ShareReward1 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 1])->where($userWhere)->sum('money');

        //今日周收益
        $low_date = (new ShareMoney())
            ->where($userWhere)
            ->where(['type' => 3])
            ->where('addtime', 'between time', [$end_time, $dq_time])
            ->group("role")
            ->select();

        $UserShareReward1 = 0;
        $UserShareReward2 = 0;
        $UserShareReward4 = 0;
        $UserShareReward5 = 0;
        foreach ($low_date as $k => $v) {
            //echo $v['role'] ."??".  $v['money']."___";
            if ($v['role'] == 1) {//推广员
                $UserShareReward1 = $v['money'];
            } elseif ($v['role'] == 2) {//代言人
                $UserShareReward2 = $v['money'];
            } elseif ($v['role'] == 3) {//一星
                $UserShareReward4 = $v['money'];
            } elseif ($v['role'] == 4) {//二星
                $UserShareReward5 = $v['money'];
            }
        }
        //周收益
        $low_word_date = (new ShareMoney())
            ->where($userWhere)
            ->where(['type' => 4])
            ->where('addtime', 'between time', [$week_start, $dq_time])
            ->find();
        $UserShareReward3 = isset($low_word_date['money']) ? $low_word_date['money'] : 0;

        $ShareUser1 = $this->getSepTeamUserRoleNumber($flags, 1);
        $ShareUser2 = $this->getSepTeamUserRoleNumber($flags, 2);
        $ShareUser3 = $this->getSepTeamUserRoleNumber($flags, 3);
        $ShareUser4 = $this->getSepTeamUserRoleNumber($flags, 4);
//        \think\Log::error(json_encode([$ShareUser1, $ShareUser2, $ShareUser3, $ShareUser4]));

        $money1 = empty($ShareUser1) ? 0 : bcdiv($data['d_reward1'], $ShareUser1, 2);
        $t_money1 = ($user['role'] != 1) ? 0 : $money1;
        $money2 = empty($ShareUser2) ? 0 : bcdiv($data['d_reward2'], $ShareUser2, 2);
        $t_money2 = ($user['role'] != 2) ? 0 : $money2;
        $money3 = empty($ShareUser3) ? 0 : bcdiv($data['d_reward3'], $ShareUser3, 2);
        $t_money3 = ($user['role'] != 3) ? 0 : $money3;
        $money4 = empty($ShareUser3) ? 0 : bcdiv($data['d_reward4'], $ShareUser3, 2);
        $t_money4 = ($user['role'] != 3) ? 0 : $money4;
        $money5 = empty($ShareUser4) ? 0 : bcdiv($data['d_reward5'], $ShareUser4, 2);
        $t_money5 = ($user['role'] != 4) ? 0 : $money5;
        $temp_arr = array();
        $temp_arr[] = array('role' => 1, 'name' => '推广员日创收', 'money' => round($data['d_reward1'], 2), 'my_money' => round($money1, 2), 'yest_money' => round($ShareReward1, 2), 'yest_user_money' => round($UserShareReward1, 2));

        $temp_arr[] = array('role' => 2, 'name' => '代言人日创收', 'money' => round($data['d_reward2'], 2), 'my_money' => round($money2, 2), 'yest_money' => round($ShareReward2, 2), 'yest_user_money' => round($UserShareReward2, 2));
        $temp_arr[] = array('role' => 3, 'name' => '一星网店日创收', 'money' => round($data['d_reward4'], 2), 'my_money' => round($money4, 2), 'yest_money' => round($ShareReward4, 2), 'yest_user_money' => round($UserShareReward4, 2));
        $temp_arr[] = array('role' => 4, 'name' => '二星网店日创收', 'money' => round($data['d_reward5'], 2), 'my_money' => round($money5, 2), 'yest_money' => round($ShareReward5, 2), 'yest_user_money' => round($UserShareReward5, 2));
        $total_money = $data['d_reward1'] + $data['d_reward2'] + $data['d_reward4'] + $data['d_reward5'];
        $total_yest_money = $ShareReward1 + $ShareReward2 + $ShareReward4 + $ShareReward5;
        $total_yest_user_money = 0;
        $my_money = 0;
        switch ($user['role']) {
            case 1:
                //$my_money = $t_money1;
                $my_money = $money1;
                $total_yest_user_money = $UserShareReward1;
                break;
            case 2:
                //$my_money = $t_money2;
                $my_money = $money2;
                $total_yest_user_money = $UserShareReward2;
                break;
            case 3:
                //$my_money = bcadd($t_money3, $t_money4);
                $my_money = $money4;
                $total_yest_user_money = $UserShareReward4;
                break;
            case 4:
                //$my_money = $t_money5;
                $my_money = $money5;
                $total_yest_user_money = $UserShareReward5;
                break;
        }
        if($user['is_adver'] == 1){
            $one = array('money' => round($data['d_reward3'], 2), 'my_money' => 0, 'yest_money' => round($ShareReward3, 2), 'yest_user_money' => round($UserShareReward3, 2));
        }else{
            $one = array('money' => round($data['d_reward3'], 2), 'my_money' => round($money3, 2), 'yest_money' => round($ShareReward3, 2), 'yest_user_money' => round($UserShareReward3, 2));
        }

        //本周创收
        $start_benzhou =  date("Y-m-d H:i:s", mktime(0,0,0,date("m"),date("d")-date("w")+1,date("Y")));    //2020-03-09 00:00:00
        $end_benzhou =  date("Y-m-d H:i:s", mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"))); //2020-03-15 23:59:59
        $start_benzhou_time  =strtotime($start_benzhou);
        $end_benzhou_time  =strtotime($end_benzhou);
        $benzhou_tongji = ShareReward::where(['user_id'=>$this->auth->id,"type"=>3])->whereBetween("addtime",[$start_benzhou_time,$end_benzhou_time])->sum("money");
        //echo ShareReward::where(['user_id'=>$this->auth->id,"type"=>3])->whereBetween("addtime",[$start_benzhou_time,$end_benzhou_time])->getLastSql();
        //上周创收
        $start_shangzhou = date('Y-m-d H:i:s', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y')));    //2020-03-02 00:00:00
        $end_shangzhou = date('Y-m-d H:i:s', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))); //2020-03-08 23:59:59
        $start_shangzhou_time  =strtotime($start_shangzhou);
        $end_shangzhou_time  =strtotime($end_shangzhou);
        $shangzhou_tongji = ShareReward::where(['user_id'=>$this->auth->id,"type"=>3])->whereBetween("addtime",[$start_shangzhou_time,$end_shangzhou_time])->sum("money");


        $this->success('成功', array("benzhou_tongji"=>$benzhou_tongji,"shangzhou_tongji"=>$shangzhou_tongji,'one' => $one, 'list' => $temp_arr, 'total_list' => array('yest_money' => round($total_yest_money, 2), 'yest_user_money' => round($total_yest_user_money, 2), 'money' => round($total_money, 2), 'my_money' => round($my_money, 2))));
    }
    public function advertising_revenue_two()
    {
        $user = (new ShareUser())->get(['user_id' => $this->user_id]); // 分销用户
        $user_flags = \db("share_user_flags")->where('user_id', $this->user_id)->find();
        $userWhere = [];
        $flags = '';
        if ($user_flags) {
            $userWhere['user_flags'] = $user_flags['user_flags'];
            $flags = $user_flags['user_flags'];
        } else {
            $userWhere['user_flags'] = '';
        }

        $data = array();
        //开始时间
        $end_time = date('Y-m-d 00:00:00');
        // 当前时间
        $dq_time = date('Y-m-d H:i:s');
        // 本周周一时间
        $week_time1 = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
        $sdefaultDate = date("Y-m-d");
        $first = 1;
        $w = date('w', strtotime($sdefaultDate));
        $week_start = date('Y-m-d H:i:s', strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days'));

        $data['d_reward7'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 7])->where($userWhere)->sum('money');
        $data['d_reward8'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 8])->where($userWhere)->sum('money');
        $data['d_reward9'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 9])->where($userWhere)->sum('money');
        $data['d_reward10'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 10])->where($userWhere)->sum('money');
        $data['d_reward11'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 11])->where($userWhere)->sum('money');
        $data['d_reward12'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 12])->where($userWhere)->sum('money');
        $data['d_reward13'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 13])->where($userWhere)->sum('money');
//        \think\Log::error(json_encode($data));

        //开始时间
        $yest_time = date("Y-m-d", strtotime("-1 day"));
        // 上周一时间
        //$week_time = date('Y-m-d H:i:s', mktime(0,0,0,date('m'),date('d')-date('w')+1-14,date('Y')));
        $week_time = date('Y-m-d H:i:s', mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 14, date('Y')));
        //echo $week_time;
        $ShareReward7 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 7])->where($userWhere)->sum('money');
        $ShareReward8 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 8])->where($userWhere)->sum('money');
        $ShareReward9 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 9])->where($userWhere)->sum('money');
        $ShareReward10 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 10])->where($userWhere)->sum('money');
        $ShareReward11 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 11])->where($userWhere)->sum('money');
        $ShareReward12 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 12])->where($userWhere)->sum('money');
        $ShareReward13 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 13])->where($userWhere)->sum('money');

        //
        $low_date = (new ShareMoney())
            ->where($userWhere)
            ->where(['type' => 7])
            ->where('addtime', 'between time', [$end_time, $dq_time])
            ->group("role")
            ->select();

        $UserShareReward1 = 0;
        $UserShareReward2 = 0;
        $UserShareReward3 = 0;
        $UserShareReward4 = 0;
        $UserShareReward5 = 0;
        $UserShareReward6 = 0;
        $UserShareReward7 = 0;
        foreach ($low_date as $k => $v) {
            //echo $v['role'] ."??".  $v['money']."___";
            if ($v['role'] == 1) {//推广员
                $UserShareReward1 = $v['money'];
            } elseif ($v['role'] == 2) {//代言人
                $UserShareReward2 = $v['money'];
            } elseif ($v['role'] == 3) {//一星
                $UserShareReward3 = $v['money'];
            } elseif ($v['role'] == 4) {//二星
                $UserShareReward4 = $v['money'];
            }
            elseif ($v['role'] == 5) {//二星
                $UserShareReward5 = $v['money'];
            }elseif ($v['role'] == 6) {//二星
                $UserShareReward6 = $v['money'];
            }elseif ($v['role'] == 7) {//二星
                $UserShareReward7 = $v['money'];
            }
        }
        //今日周收益
        $low_date = (new ShareMoney())
            ->where($userWhere)
            ->where(['type' => 3])
            ->where('addtime', 'between time', [$end_time, $dq_time])
            ->group("role")
            ->select();

        $ShareUser1 = $this->getSepTeamUserRoleNumber($flags, 1);
        $ShareUser2 = $this->getSepTeamUserRoleNumber($flags, 2);
        $ShareUser3 = $this->getSepTeamUserRoleNumber($flags, 3);
        $ShareUser4 = $this->getSepTeamUserRoleNumber($flags, 4);
        $ShareUser5 = $this->getSepTeamUserRoleNumber($flags, 5);
        $ShareUser6 = $this->getSepTeamUserRoleNumber($flags, 6);
        $ShareUser7 = $this->getSepTeamUserRoleNumber($flags, 7);
//        \think\Log::error(json_encode([$ShareUser1, $ShareUser2, $ShareUser3, $ShareUser4]));

        $money1 = empty($ShareUser1) ? 0 : bcdiv($data['d_reward7'], $ShareUser1, 2);

        $money2 = empty($ShareUser2) ? 0 : bcdiv($data['d_reward8'], $ShareUser2, 2);

        $money3 = empty($ShareUser3) ? 0 : bcdiv($data['d_reward9'], $ShareUser3, 2);

        $money4 = empty($ShareUser4) ? 0 : bcdiv($data['d_reward10'], $ShareUser4, 2);

        $money5 = empty($ShareUser5) ? 0 : bcdiv($data['d_reward11'], $ShareUser5, 2);
        $money6 = empty($ShareUser6) ? 0 : bcdiv($data['d_reward12'], $ShareUser6, 2);
        $money7 = empty($ShareUser7) ? 0 : bcdiv($data['d_reward13'], $ShareUser7, 2);
        if($user['is_adver'] == 1){
            $money1 = 0;
            $money2 = 0;
            $money3 = 0;
            $money4 = 0;
            $money5 = 0;
            $money6 = 0;
            $money7 = 0;
        }
        $temp_arr = array();
        $temp_arr[] = array('role' => 1, 'name' => '代言人日创收', 'money' => round($data['d_reward7'], 2), 'my_money' => round($money1, 2), 'yest_money' => round($ShareReward7, 2), 'yest_user_money' => round($UserShareReward1, 2));
        $temp_arr[] = array('role' => 2, 'name' => '创客日创收', 'money' => round($data['d_reward8'], 2), 'my_money' => round($money2, 2), 'yest_money' => round($ShareReward8, 2), 'yest_user_money' => round($UserShareReward2, 2));
        $temp_arr[] = array('role' => 3, 'name' => '网店店长日创收', 'money' => round($data['d_reward9'], 2), 'my_money' => round($money3, 2), 'yest_money' => round($ShareReward9, 2), 'yest_user_money' => round($UserShareReward3, 2));
        $temp_arr[] = array('role' => 4, 'name' => '网店店主日创收', 'money' => round($data['d_reward10'], 2), 'my_money' => round($money4, 2), 'yest_money' => round($ShareReward10, 2), 'yest_user_money' => round($UserShareReward4, 2));
        $temp_arr[] = array('role' => 4, 'name' => '一级经销商日创收', 'money' => round($data['d_reward11'], 2), 'my_money' => round($money5, 2), 'yest_money' => round($ShareReward11, 2), 'yest_user_money' => round($UserShareReward5, 2));
        $temp_arr[] = array('role' => 4, 'name' => '二级经销商日创收', 'money' => round($data['d_reward12'], 2), 'my_money' => round($money6, 2), 'yest_money' => round($ShareReward12, 2), 'yest_user_money' => round($UserShareReward6, 2));
        $temp_arr[] = array('role' => 4, 'name' => '三级经销商日创收', 'money' => round($data['d_reward13'], 2), 'my_money' => round($money7, 2), 'yest_money' => round($ShareReward13, 2), 'yest_user_money' => round($UserShareReward7, 2));
        $total_money = $data['d_reward7'] + $data['d_reward8'] + $data['d_reward9'] + $data['d_reward10'] + $data['d_reward11'] + $data['d_reward12'] + $data['d_reward13'];
        $total_yest_money = $ShareReward7 + $ShareReward8 + $ShareReward9 + $ShareReward10 + $ShareReward11 + $ShareReward12 + $ShareReward13;
        $total_yest_user_money = 0;
        $my_money = 0;
        switch ($user['role']) {
            case 1:
                //$my_money = $t_money1;
                $my_money = $money1;
                $total_yest_user_money = $UserShareReward1;
                break;
            case 2:
                //$my_money = $t_money2;
                $my_money = $money2;
                $total_yest_user_money = $UserShareReward2;
                break;
            case 3:
                //$my_money = bcadd($t_money3, $t_money4);
                $my_money = $money3;
                $total_yest_user_money = $UserShareReward3;
                break;
            case 4:
                //$my_money = $t_money5;
                $my_money = $money4;
                $total_yest_user_money = $UserShareReward4;
                break;
            case 5:
                //$my_money = $t_money5;
                $my_money = $money5;
                $total_yest_user_money = $UserShareReward5;
                break;
            case 6:
                //$my_money = $t_money5;
                $my_money = $money6;
                $total_yest_user_money = $UserShareReward6;
                break;
            case 7:
                //$my_money = $t_money5;
                $my_money = $money7;
                $total_yest_user_money = $UserShareReward7;
                break;
        }
        $this->success('成功', array( 'list' => $temp_arr, 'total_list' => array('yest_money' => round($total_yest_money, 2), 'yest_user_money' => round($total_yest_user_money, 2), 'money' => round($total_money, 2), 'my_money' => round($my_money, 2))));
    }
    public function advertising_revenue_three()
    {
        $user = (new ShareUser())->get(['user_id' => $this->user_id]); // 分销用户
        $user_flags = \db("share_user_flags")->where('user_id', $this->user_id)->find();
        $userWhere = [];
        $flags = '';
        if ($user_flags) {
            $userWhere['user_flags'] = $user_flags['user_flags'];
            $flags = $user_flags['user_flags'];
        } else {
            $userWhere['user_flags'] = '';
        }

        $data = array();
        //开始时间
        $end_time = date('Y-m-d 00:00:00');
        // 当前时间
        $dq_time = date('Y-m-d H:i:s');
        // 本周周一时间
        $week_time1 = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
        $sdefaultDate = date("Y-m-d");
        $first = 1;
        $w = date('w', strtotime($sdefaultDate));
        $week_start = date('Y-m-d H:i:s', strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days'));

        $data['d_reward7'] = (new Reward())->where('addtime', 'between time', [$end_time, $dq_time])->where(['type' => 7])->where($userWhere)->sum('money');
//        \think\Log::error(json_encode($data));

        //开始时间
        $yest_time = date("Y-m-d", strtotime("-1 day"));
        // 上周一时间
        //$week_time = date('Y-m-d H:i:s', mktime(0,0,0,date('m'),date('d')-date('w')+1-14,date('Y')));
        $week_time = date('Y-m-d H:i:s', mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 14, date('Y')));
        //echo $week_time;
        $ShareReward7 = (new ShareReward())->where('addtime', 'between time', [$yest_time, $end_time])->where(['type' => 7])->where($userWhere)->sum('money');

        //
        $low_date = (new ShareMoney())
            ->where($userWhere)
            ->where(['type' => 7])
            ->where('addtime', 'between time', [$end_time, $dq_time])
            ->group("role")
            ->select();

        $UserShareReward1 = 0;

        foreach ($low_date as $k => $v) {
            //echo $v['role'] ."??".  $v['money']."___";
            if ($v['role'] == 1) {//推广员
                $UserShareReward1 = $v['money'];
            }
        }
        //今日周收益
        $low_date = (new ShareMoney())
            ->where($userWhere)
            ->where(['type' => 3])
            ->where('addtime', 'between time', [$end_time, $dq_time])
            ->group("role")
            ->select();

        $ShareUser1 = $this->getSepTeamUserRoleNumber($flags, 1);

//        \think\Log::error(json_encode([$ShareUser1, $ShareUser2, $ShareUser3, $ShareUser4]));

        $money1 = empty($ShareUser1) ? 0 : bcdiv($data['d_reward7'], $ShareUser1, 2);


        if($user['is_adver'] == 1){
            $money1 = 0;

        }
        $temp_arr = array();
        $temp_arr[] = array('role' => 1, 'name' => '推广员日创收', 'money' => round($data['d_reward7'], 2), 'my_money' => round($money1, 2), 'yest_money' => round($ShareReward7, 2), 'yest_user_money' => round($UserShareReward1, 2));

        $total_money = $data['d_reward7'];
        $total_yest_money = $ShareReward7;
        $total_yest_user_money = 0;
        $my_money = 0;
        switch ($user['role']) {
            case 1:
                //$my_money = $t_money1;
                $my_money = $money1;
                $total_yest_user_money = $UserShareReward1;
                break;
        }
        $this->success('成功', array( 'list' => $temp_arr, 'total_list' => array('yest_money' => round($total_yest_money, 2), 'yest_user_money' => round($total_yest_user_money, 2), 'money' => round($total_money, 2), 'my_money' => round($my_money, 2))));
    }
    /**
     * 收益
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    /*public function get_goods_reward()
    {
$offset = $this->request->post("offset"); // 第几页
        $offset = empty($offset) ? 0 : bcsub($offset, 1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 10 : $limit;
        $page = empty($offset) ? 0 : bcmul($offset, $limit);

        $day = date('Y-m-d');
        $todaymonth = $this->_get_ctime($day, 'month');
        $whereSql['createtime'] = ['between', [$todaymonth['start_time'], $todaymonth['end_time']]];
        //$whereSql['goods_id'] = ['IN', [1, 2, 3, 4, 5, 6]];
        $whereSql['one_day'] = ['IN', [0,5]];
        $whereSql['status'] = ['IN', [1, 2]];//qi
        $whereSql['share_retreat'] = 0;
        $lists = Db::table('shopro_order')->field('user_id,goods_id,total_fee,createtime')
            ->where($whereSql)
            ->order('createtime', 'DESC')
            ->group('goods_id')
            ->limit($page, $limit)->select();

        $goodsWhere['createtime'] = ['between', [$todaymonth['start_time'], $todaymonth['end_time']]];
        $goodsWhere['status'] = 1;
        $goodsWhere['share_retreat'] = 0;
        foreach ($lists as $key => $value) {
            $goodsWhere['goods_id'] = $value['goods_id'];
            $lists[$key]['goods_num'] = Db::table('shopro_order')->where($goodsWhere)->count();
            $goodsinfo = Db::table('shopro_goods')->where(['id' => $value['goods_id']])->find();
            $userinfo = Db::table('user')->where(['id' => $value['user_id']])->find();
            $lists[$key]['name'] = $goodsinfo['title'];
            $lists[$key]['nickname'] = $userinfo['nickname'];
            $lists[$key]['addtime'] = $value['createtime'];
        }

        $today = $this->_get_ctime($day, 'day');
        $yestoday = $this->_get_ctime($day, 'yestomonth');

        $todayAmount = $this->_calcUserReward($today['start_time'], $today['end_time']);

        $whereToMonth['user_id'] = $this->user_id;
        $totalAmount = Db::table('share_goods_reward')->where($whereToMonth)->sum('money');

        $data['total_profit'] = round($totalAmount + $todayAmount, 2);//我的总收益

//        $whereToMonth['addtime'] = ['between', [$yestoday['start_time'], $yestoday['end_time']]];
        $whereToMonth['month'] = ['like', "%" . date('Y-m') . "%"];
        $tomonthAmount = Db::table('share_goods_reward')->where($whereToMonth)->sum('money');
        $data['today_num'] = round($tomonthAmount + $todayAmount, 2);//当月

        $whereYesToTime['user_id'] = $this->user_id;
//        $whereYesToTime['addtime'] = ['between', [$yestoday['start_time'], $yestoday['end_time']]];
        $tomonthDate = date('Y-m', strtotime("$day -1 month"));
        $whereYesToTime['month'] = ['like', "%" . $tomonthDate . "%"];
        $data['yestoday_num'] = Db::table('share_goods_reward')->where($whereYesToTime)->sum('money');

        //qi 11.1
        // $day_whereSql['createtime'] = ['between', [$today['start_time'], $today['end_time']]];
        // $day_whereSql['goods_id'] = ['IN', [1, 2, 3, 4, 5, 6]];
        $day_whereSql ['one_day'] = ['IN', [0,5]];
        $day_whereSql['status'] = ['IN', [1, 2]];
        $day_whereSql['share_retreat'] = 0;
        $count = Db::table('shopro_order')->where($day_whereSql)->count();
        $count = $count > 0 ? $count : 0;//总单量
        //qi

        $creation_money = Db::name("config")->where(['name' => 'creation_money'])->find();
        if($creation_money){
            $lc_money = $creation_money['value'];
        }else{
            $lc_money = 100;
        }

        $data['total_amount_sum'] = $count * $lc_money;
        //上月联创总收益
        $time = strtotime('-1 month');
        $mon_str_time = strtotime(date('Y-m-d H:i:s', mktime(0, 0, 0, date('m', $time), 01, date('Y', $time)))); //php上个月的开始时间
        $mon_end_time = strtotime(date('Y-m-d H:i:s', mktime(23, 59, 59, date('m', $time), date('t', $time), date('Y', $time)))); //上个月的结束时间
        $mon_whereSql['createtime'] = ['between', [$mon_str_time, $mon_end_time]];
        //$mon_whereSql['goods_id'] = ['IN', [1, 2, 3, 4, 5, 6]];
        $mon_whereSql['one_day'] = ['IN', [0,5]];
        $mon_whereSql['status'] = ['IN', [1, 2]];
        $mon_whereSql['share_retreat'] = 0;
        $mon_count = Db::table('shopro_order')->where($mon_whereSql)->count();

        $mon_count = $mon_count > 0 ? $mon_count : 0;//上月的单量
        $data['yestoday_num_sum'] = $mon_count * $lc_money;

        $data['lists'] = $lists;
        $this->success('成功', $data);
    }*/
    public function get_goods_reward()
    {

        $offset = $this->request->post("offset"); // 第几页
        $offset = empty($offset) ? 0 : bcsub($offset, 1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 10 : $limit;
        $page = empty($offset) ? 0 : bcmul($offset, $limit);

        $day = date('Y-m-d');
        $todaymonth = $this->_get_ctime($day, 'month');
        $whereSql['createtime'] = ['between', [$todaymonth['start_time'], $todaymonth['end_time']]];
        //$whereSql['goods_id'] = ['IN', [1, 2, 3, 4, 5, 6]];
        $whereSql['one_day'] = ['IN', [0, 5]];
        $whereSql['status'] = ['IN', [1, 2]];//qi
        $whereSql['share_retreat'] = 0;
        $lists = Db::table('shopro_order')->field('user_id,goods_id,total_fee,createtime')
            ->where($whereSql)
            ->order('createtime', 'DESC')
            ->group('goods_id')
            ->limit($page, $limit)->select();

        $goodsWhere['createtime'] = ['between', [$todaymonth['start_time'], $todaymonth['end_time']]];
        $goodsWhere['status'] = 1;
        $goodsWhere['share_retreat'] = 0;
        foreach ($lists as $key => $value) {
            $goodsWhere['goods_id'] = $value['goods_id'];
            $lists[$key]['goods_num'] = Db::table('shopro_order')->where($goodsWhere)->count();
            $goodsinfo = Db::table('shopro_goods')->where(['id' => $value['goods_id']])->find();
            $userinfo = Db::table('user')->where(['id' => $value['user_id']])->find();
            $lists[$key]['name'] = $goodsinfo['title'];
            $lists[$key]['nickname'] = $userinfo['nickname'];
            $lists[$key]['addtime'] = $value['createtime'];
        }


        //当天个人收益
        $userNum = Db::table('share_user')->where(['is_union' => 1])->count();
        $userNum = $userNum > 0 ? $userNum : 0;
        if ($userNum <= 0) {
            $todayAmount = 0;
        } else {
            $yestoday_num_sum = (new CommonShare())->rewardMoney("today");
            $todayAmount = round($yestoday_num_sum / $userNum, 2);
        }
        $is_union = Db::table('share_user')->where(['user_id' => $this->user_id])->value("is_union");
        if ($is_union == 0) {
            $todayAmount = 0;
        }
        $whereToMonth['user_id'] = $this->user_id;
        $totalAmount = Db::table('share_goods_reward')->where($whereToMonth)->sum('money');

        $data['total_profit'] = round($totalAmount + $todayAmount, 2);//我的总收益

//        $whereToMonth['addtime'] = ['between', [$yestoday['start_time'], $yestoday['end_time']]];
        $whereToMonth['month'] = ['like', "%" . date('Y-m') . "%"];
        $tomonthAmount = Db::table('share_goods_reward')->where($whereToMonth)->sum('money');
        $data['today_num'] = round($tomonthAmount + $todayAmount, 2);//当月
        //我的上个月收益
        $whereYesToTime['user_id'] = $this->user_id;
//        $whereYesToTime['addtime'] = ['between', [$yestoday['start_time'], $yestoday['end_time']]];
        $tomonthDate = date('Y-m', strtotime("$day -1 month"));
        $whereYesToTime['month'] = ['like', "%" . $tomonthDate . "%"];
        $data['yestoday_num'] = Db::table('share_goods_reward')->where($whereYesToTime)->sum('money');

        //总收益
        $total_amount_sum = (new CommonShare())->rewardMoney();
        $data['total_amount_sum'] = $total_amount_sum;
        //上月联创总收益
        $yestoday_num_sum = (new CommonShare())->rewardMoney("last month");
        $data['yestoday_num_sum'] = $yestoday_num_sum;

        $data['lists'] = $lists;
        $this->success('成功', $data);
    }

    /**
     * 联创收益
     */
    public function rewardList()
    {
        // 我的总收益
        $type = input('type') ? input('type') : 0;
        $offset = input('offset');
        $data['total_profit'] = []; // 总收益

        $creation_money = Db::name("config")->where(['name' => 'creation_money'])->find();
        if ($creation_money) {
            $lc_money = $creation_money['value'];
        } else {
            $lc_money = 100;
        }

        if ($type) {
            // 联创总收益
            //$day_whereSql['goods_id'] = ['IN', [1, 2, 3, 4, 5, 6]];
            $day_whereSql['one_day'] = ['IN', [0, 5]];

            $day_whereSql['status'] = ['IN', [1, 2]];
            $day_whereSql['share_retreat'] = 0;
            $count = Db::table('shopro_order')->where($day_whereSql)->field('id,createtime')->select();


            foreach ($count as $v) {
                $money = $lc_money;
                $data['total_profit'][] = ['id' => $v['id'], 'title' => '联创总收益', 'money' => $money, 'createtime' => date('Y-m-d H:i:s', $v['createtime'])];
            }
        } else {
            $today = $this->_get_ctime(date('Y-m-d'), 'day');
            //$whereSql['goods_id'] = ['IN', [1, 2, 3, 4, 5, 6]];
            $whereSql['one_day'] = ['IN', [0, 5]];
            $whereSql['status'] = ['IN', [1, 2]];
            $whereSql['share_retreat'] = 0;
            $whereSql['createtime'] = ['between', [$today['start_time'], $today['end_time']]];

            $count = Db::table('shopro_order')->where($whereSql)->field('id,createtime')->select();
            $userNum = Db::table('share_user')->where(['is_union' => 1])->count();
            $isUnion = Db::table('share_user')->where(['user_id' => $this->user_id, 'is_union' => 1])->count();

            if ($isUnion && $count && $userNum) {
                foreach ($count as $v) {
                    $money = $lc_money / $userNum;
                    $data['total_profit'][] = ['id' => $v['id'], 'title' => '我的联创收益', 'money' => $money, 'createtime' => date('Y-m-d H:i:s', $v['createtime'])];
                }
            }

            $whereToMonth['user_id'] = $this->user_id;
            $totalAmount = Db::table('share_goods_reward')->where($whereToMonth)->field('id,money,addtime as createtime')->select();
            foreach ($totalAmount as $v) {
                $data['total_profit'][] = ['id' => $v['id'], 'title' => '我的联创收益', 'money' => $v['money'], 'createtime' => date('Y-m-d H:i:s', $v['createtime'])];
            }
        }

        if (!count($data['total_profit'])) {
            $data = [];
        } else {
            $data = array_chunk($data['total_profit'], 10)[$offset - 1];
        }

//        array_multisort(array_column($list,'createtime'),SORT_DESC,$list);
        $this->success('成功', $data);
    }

    private function getSepTeamUser($userId)
    {
        $teamlist = Db::table('share_user')->where(['is_sep_income' => 1])->select();
        $teamUidArr = [];
        $noteamUidArr = [];
        if (!empty($teamlist)) {
            $user = Db::name('share_user')->where('user_id', $userId)->find();

            $sep_user = 0;
            foreach ($teamlist as $val) {
                if (strpos($user['role_url'], '/' . $val['user_id'] . '/') !== false) {
                    $sep_user = $val['user_id'];
                    break;
                }
            }

            if ($sep_user > 0) {
                $puserlist = Db::table('share_user')->where(['role_url' => ['like', "%" . $sep_user . "%"]])
                    ->order('id DESC')->select();
                $userIdsStr = '';
                foreach ($puserlist as $vv) {
                    $userIdsStr = $userIdsStr . $val['role_url'] . '/' . $vv['user_id'];
                }

                $userArray = explode('/', $userIdsStr);
                $teamArray = array_filter($userArray);
                $teamArray = array_merge($teamArray, [$val['user_id']]);
                if (in_array($userId, $teamArray)) {
                    foreach ($teamArray as $k => $uid) {
                        if ($uid >= $val['user_id']) {
                            $teamUidArr[$k] = $uid;
                        } else {
                            $noteamUidArr[$k] = $uid;
                        }
                    }
                }
            }

        }
        $teamUidArr = array_unique($teamUidArr);
        $noteamUidArr = array_unique($noteamUidArr);
        return ['team_user' => $teamUidArr, 'noteam_user' => $noteamUidArr];
    }

//    public function getSepTeamUserNew($userId)
//    {
//        $teamlist = Db::table('share_user')->where(['is_sep_income' => 1])->select();
//        $sep_user = 0;
//        if (!empty($teamlist)) {
//            $user = Db::name('share_user')->where('user_id', $userId)->find();
//
//            foreach ($teamlist as $val) {
//                if ($userId == $val['user_id']) {
//                    $sep_user = $val['user_id'];
//                    break;
//                }
//
//                if (strpos($user['role_url'], '/' . $val['user_id'] . '/') !== false) {
//                    $sep_user = $val['user_id'];
//                    break;
//                }
//            }
//
//        }
//
//        return $sep_user;
//    }

    private function getSepTeamUserRoleNumber($user_flags, $role)
    {
        if ($user_flags) {
            return Db::name('share_user u')
                ->join('share_user_flags f', 'f.user_id = u.user_id')
                ->where('u.role', $role)
                ->where('u.is_adver', 0)
                ->where('f.user_flags', $user_flags)
                ->count();
        } else {
            $items = Db::name('share_user')->field('user_flags', 'is not null')->field('user_flags')->select();
            $all = Db::name('share_user')->where('role', $role)->where('is_adver', 0)->count();

            $arr = array_column($items, 'user_flags');
            $count = Db::name('share_user u')
                ->join('share_user_flags f', 'f.user_id = u.user_id')
                ->where('u.role', $role)
                ->where('u.is_adver', 0)
                ->where('f.user_flags', 'in', $arr)
                ->count();

            return $all - $count;
        }

    }

    private function _calcUserReward($starttime = '', $endtime = '')
    {
        $isUnion = Db::table('share_user')->where(['user_id' => $this->user_id, 'is_union' => 1])->count();
        if ($isUnion <= 0) {
            return 0;
        }
        if ($starttime && $endtime) {
            $whereSql['createtime'] = ['between', [$starttime, $endtime]];
        }
        // $whereSql['goods_id'] = ['IN', [1, 2, 3, 4, 5, 6]];
        $whereSql['one_day'] = ['IN', [0, 5]];
        $whereSql['status'] = ['IN', [1, 2]];
        $whereSql['share_retreat'] = 0;
        $count = Db::table('shopro_order')->where($whereSql)->count();
        //echo $count;
        $count = $count > 0 ? $count : 0;

        $userNum = Db::table('share_user')->where(['is_union' => 1])->count();
        $userNum = $userNum > 0 ? $userNum : 0;
        if ($userNum <= 0) {
            return 0;
        }
        //qi10.31
        $creation_money = Db::name("config")->where(['name' => 'creation_money'])->find();
        if ($creation_money) {
            $lc_money = $creation_money['value'];
        } else {
            $lc_money = 100;
        }

        $amount = $lc_money * $count / $userNum;
        return sprintf('%.2f', $amount);
    }

    private function _get_ctime($day_time, $type = 'day', $is_format = false)
    {
        $beginDate = date('Y-m-01', strtotime($day_time));
        if ($type == 'day') {
            $beginDate = date('Y-m-d', strtotime($day_time));
            $month_end = strtotime(date('Y-m-d', strtotime("$beginDate +1 day")));
        } else if ($type == 'yestoday') {
            $beginDate = date('Y-m-d', strtotime("$day_time -1 day"));
            $month_end = strtotime(date('Y-m-d', strtotime("$beginDate +1 day")));
        } else if ($type == 'month') {
            $month_end = strtotime(date('Y-m-d', strtotime("$beginDate +1 month")));
            //$month_end= strtotime("next day", strtotime($endDate)) - 1;//指定年月份月末时间戳
        } else if ($type == 'yestomonth') {
            $beginDate = date('Y-m-d', strtotime("$day_time -1 month"));
            $month_end = strtotime(date('Y-m-d', strtotime("$beginDate +1 month")));
            //$month_end= strtotime("next day", strtotime($endDate)) - 1;//指定年月份月末时间戳
        }

        $day_arr['start_time'] = strtotime(date('Y-m-d H:i:s', strtotime($beginDate)));
        $day_arr['end_time'] = strtotime(date('Y-m-d H:i:s', $month_end));
        if ($is_format == true) {
            $day_arr['start_time'] = date('Y-m-d H:i:s', strtotime($beginDate));
            $day_arr['end_time'] = date('Y-m-d H:i:s', $month_end);
        }
        return $day_arr;
    }

    public function getMutualList()
    {
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $srart = strtotime($starttime);
        $end = strtotime($endtime);
        $params['wallet_type'] = 'mutual';
        $params['user_id'] = $this->user_id;
        $type = $this->request->get("type");
        if (!in_array($type, [1, 2])) {
            $this->error('参数错误');
        }
//        if ($type == 1) {
//            $list = Db::table('shopro_user_wallet_log')->where($params)->whereBetween("createtime",[$srart,$end])->where('wallet', '>=', 0)->order('id', 'DESC')->paginate(10);
//        } else if ($type == 2) {
//            $list = Db::table('shopro_user_wallet_log')->where($params)->whereBetween("createtime",[$srart,$end])->where('wallet', '<', 0)->order('id', 'DESC')->paginate(10);
//        }
        //取消收入支出，查询全部
        $list = Db::table('shopro_user_wallet_log')->where($params)->whereBetween("createtime",[$srart,$end])->order('id', 'DESC')->paginate(10);
        $data = $list->items();
        $money_type = [
            "1" =>  "零售收益",
            "2" =>  "批发收益",
            "3" =>  "日广告收益",
            "4" =>  "周广告收益",
            "5" =>  "多商户进货成本",
            "6" =>  "多商户一星网点分佣",
            "7" =>  "购买商品",
        ];
        foreach ($data as &$w) {
            if ($w['before'] >= $w['after']) {
                $w['flag'] = '-';
            } else {
                $w['flag'] = '+';
            }
            $w['goods_title'] = ""; //商品名称
            $w['form_username'] = "";   //来源用户名称
            $w['money_type_text'] = "";
            $w['wallet'] = abs($w['wallet']);
            if($w['money_type']>0){
                $w['money_type_text'] = $money_type[$w['money_type']];
            }
            if ($w['item_id'] != '') {
                $item = OrderItem::where('order_id', $w['item_id'])->order('id', 'asc')->find();

                $w['goods_title'] = isset($item->goods_title) ? $item->goods_title : "";
                if($w['money_type'] < 7 && isset($item->goods_title)){
                    $w['goods_title'] = $w['money_type_text'].":".$item->goods_title;
                }
                if($item){
                    $user = User::where(['id'=>$item->user_id])->find();
                    if($user){
                            $w['form_username'] = $user->username;
                    }
                }
            }
            $w['come_title'] = '';
            if(($w['money_type'] == 1 || $w['money_type'] == 2) && $w['item_id'] > 0){
                $d = Db::name("shopro_order o")
                    ->join("user u","u.id = o.user_id")
                    ->field("u.mobile")
                    ->where(['o.id'=>$w['item_id']])
                    ->find();
                if($d){
                    $w['come_title'] = "来自-".$d['mobile'];
                }

            }
            $w['createtime'] = date('Y-m-d H:i:s', $w['createtime']);
        }
        //$list->data = $data;
        $res = [
            "total" => $list->total(),
            "per_page" => $list->listRows(),
            'current_page' => $list->currentPage(),
            'last_page' => $list->lastPage(),
            'data' => $data
        ];
        $this->success('互助金消费明细', $res);
    }

    /**
     * 余额日志
     */
    public function user_money_log()
    {
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $srart = strtotime($starttime);
        $end = strtotime($endtime);
        $type = $this->request->post("type");
        $is_old = $this->request->post("is_old", 0);

        $offset = $this->request->post("offset"); // 第几页
        $limit = 10;
        $where['user_id'] = $this->user_id;
        $where['is_old'] = $is_old;
        if ($type) {
            $where['type'] = $type;
        }

        $lists = MoneyLog::where($where)
            ->whereBetween("createtime",[$srart,$end])
            ->order('id', 'DESC')
            ->limit(($offset - 1) * $limit, $limit)->select();
        foreach ($lists as $key => $value) {
            //$u = Db::name("user")->where(['id' => $value['user_id']])->find();
            $lists[$key]->createtime = date('Y-m-d H:i:s', $value['createtime']);
            // $lists[$key]->mobile = $u['mobile'];
            if ($value['before'] >= $value['after']) {
                if (!(strpos($value['money'], '-') !== false)) {
                    $lists[$key]['money'] = '-' . $value['money'];
                }
            } else {
                $lists[$key]['money'] = '+' . $value['money'];
            }
            //增加 余额转让   来自131****8888      2022-10-26 18:45:26       +-10
            $user  =Db::name("user")->where(['mobile' => $value['mobile']])->find();
            if($user){
                $lists[$key]['username'] = $user["username"];
            }
        }
        $this->success('成功', $lists);
    }

    /**
     * 积分日志
     */
    public function user_score_log()
    {
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $srart = strtotime($starttime);
        $end = strtotime($endtime);
        $type = $this->request->post("type");

        $offset = $this->request->post("offset"); // 第几页
        $offset = empty($offset) ? 0 : bcsub($offset, 1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 10 : $limit;
        $page = empty($offset) ? 0 : bcmul($offset, $limit);
        $where['user_id'] = $this->user_id;
        if ($type) {
            $where['type'] = $type;
        }

        $lists = ScoreLog::where($where)
            ->order('id', 'DESC')
            ->whereBetween("createtime",[$srart,$end])
            ->limit($page, $limit)->select();
        //1变更积分2商品订单3签到赠送积分4积分充值5兑换添加卷6积分转增7余额提现8、 9。积分兑换股票
        $typeArr = [
            "1" =>  "变更积分",
            "2" =>  "商品订单",
            "3" =>  "签到赠送积分",
            "4" =>  "积分充值",
            "5" =>  "兑换提货卷",
            "6" =>  "积分转增",
            "7" =>  "余额提现",
            "8" =>  "积分兑换股票",
            "9" =>  "积分兑换股票",
        ];
        foreach ($lists as $key => $value) {
            $lists[$key]['goods_title'] = "";
            if(isset($value['goods_id'])){
                $goods= Goods::where(['id'=>$value['goods_id']])->find();
                if($goods){
                    $lists[$key]['goods_title'] = $goods->title;
                }
            }
            //$lists[$key]->type_name =  $this->get_type($value->type);
            $lists[$key]->type_name =  $typeArr[$value['type']];
            $lists[$key]->createtime = date('Y-m-d H:i:s', $value['createtime']);
           /* $u = Db::name("user")->where(['id' => $value['user_id']])->find();
            $lists[$key]->mobile = $u['mobile'];*/
        }
        $this->success('成功', $lists);
    }

    /**
     * 转赠
     */
    public function price_subgift()
    {
        $money_transfer = Db::name("config")->where(['name' => 'money_transfer'])->find();
        if ($money_transfer && $money_transfer['value'] == 2) {
            $this->error(__('亲，此功能暂未开放···'));
        }
        $mobile = $this->request->post("mobile"); // 手机号
        $price = $this->request->post("money"); // 金额
        $is_old = $this->request->post("is_old", 0); // 1是老金额
        $captcha = $this->request->post("captcha");//短信验证码
        if (!$captcha) {
            $this->error(__('验证码不能为空'));
        }
        $user = $this->auth->getUser();
        $config_test_code = Db::name("config")->where(['name' => "test_code"])->find();
        $test_code = $config_test_code ? $config_test_code['value'] : 134913;
        if (!White::verifyMobileWhite($this->auth->mobile, $captcha)) {
            $arr_temp = array(13131388888,
                18213345601, 18213345602, 18213345603, 18213345604, 18213345605, 18213345606, 18213345607, 18213345608, 18213345609, 18213345610, 18213345611, 18213345612, 18213345613, 18213345614, 18213345615, 18213345616, 18213345617, 18213345619, 18213345620, 18213345621, 18213345622, 18213345623, 18213345624, 18213345625, 18213345626, 18213345627, 18213345628, 13136281919
            );
            $is_true = true;
            if (in_array($this->auth->mobile, $arr_temp)) {
                if ($this->auth->mobile == '13131388888' && $captcha == '131313') {
                    $is_true = false;
                }
                if ($this->auth->mobile != '13131388888' && $captcha == '1111') {
                    $is_true = false;
                }
            }

            if ($is_true) {
                if ($user->staff == 2 && $captcha != $test_code) {
                    $this->error(__('验证码不正确'));
                }
                if ($user->staff != 2) {
                    if (!Sms::check($this->auth->mobile, $captcha, 'transferpoints')) {
                        $this->error(__('验证码不正确'));
                    }
                }
            }
        }

        $fttuser = User::getByMobile($mobile);
        if (empty($fttuser)) {
            $this->error('手机号不存在');
        }

        if ($fttuser['id'] == $this->auth->id) {
            $this->error('自己不能给自己转赠');
        }
        if ($user["staff"] == 2 && $fttuser['staff'] != 2) {
            $this->error('此账号是测试号，无法转增');
        }
        if ($user["staff"] != 2 && $fttuser['staff'] == 2) {
            $this->error('对方账号是测试号，无法转增');
        }

        if (empty($price)) {
            $this->error('转赠金额需要大于0');
        }
        if ($price < 0.01) {
            $this->error('转赠金额需要大于0.01');
        }
        if ($is_old == 1) {
            $share_user = (new ShareUser())->get(['user_id' => $this->auth->id]); // 用户积分
            if ((double)$share_user['old_price'] < (double)$price) {
                $this->error('余额不足');
            }
            $before1 = $share_user->old_price;
            $after1 = $share_user->old_price - $price;
            $share_user->old_price = $after1;
            $share_user->save();
            $subgift_user = (new ShareUser())->get(['user_id' => $fttuser['id']]); // 转赠用户
            $before = $subgift_user->old_price;
            $after = $subgift_user->old_price + $price;
            $subgift_user->old_price = $after;
            $subgift_user->save();
            MoneyLog::create(['user_id' => $this->auth->id, 'money' => abs($price), 'before' => $before1, 'after' => $after1, 'type' => 7, 'mobile' => $mobile, 'memo' => "余额转赠", 'is_old' => 1]);
            MoneyLog::create(['user_id' => $fttuser['id'], 'money' => abs($price), 'before' => $before, 'after' => $after, 'type' => 7, 'mobile' => $this->auth->mobile, 'memo' => "余额转赠", 'is_old' => 1]);
        } else {
            $share_user = (new ShareUser())->get(['user_id' => $this->auth->id]); // 用户积分
            if ((double)$share_user['price'] < (double)$price) {
                $this->error('余额不足');
            }
            $before1 = $share_user->price;
            $after1 = $share_user->price - $price;
            $share_user->price = $after1;
            $share_user->save();
            $subgift_user = (new ShareUser())->get(['user_id' => $fttuser['id']]); // 转赠用户
            $before = $subgift_user->price;
            $after = $subgift_user->price + $price;
            \addons\shopro\model\User::money(-$price, $this->auth->id, 'money_subgift', '', '余额转赠', [
                'cz_type' => 7,
                'mobile' => $mobile,
            ]);
            \addons\shopro\model\User::money($price, $fttuser['id'], 'money_subgift', '', '余额转赠', [
                'cz_type' => 7,
                'mobile' => $this->auth->mobile,
            ]);
            $subgift_user->price = $after;
            $subgift_user->save();
        }

        $this->success('转赠成功');
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 申请联创
     */
    public function unionAdd()
    {
        $name = $this->request->post("name");
        $mobile = $this->request->post("mobile");
        $reg_mobile = $this->request->post("reg_mobile");
        $address = $this->request->post("address");
        $money = $this->request->post("money");
        $u_data = Db::name("user")->where(['mobile' => $mobile])->find();
        if (!$u_data) {
            //$this->error('手机号错误');
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号格式错误'));
        }
        /* if (!Validate::regex($reg_mobile, "^1\d{10}$")) {
             $this->error(__('推荐人手机号格式错误'));
         }
         $u_data = Db::name("user")->where(['mobile' => $reg_mobile])->find();
         if (!$u_data) {
             // $this->error('推荐人手机号错误');
         }*/
        $share_data = Db::name("share_user")->where(['user_id' => $this->auth->id])->find();
        if ($share_data['price'] < $money) {
            $this->error('余额不足');
        }
        $in_data['name'] = $name;
        $in_data['money'] = $money;
        $in_data['mobile'] = $mobile;
        $in_data['reg_mobile'] = $reg_mobile;
        $in_data['address'] = $address;
        $in_data['user_id'] = $this->auth->id;
        Db::name("union")->insert($in_data);
        (new ShareUser)->userPriceLog($this->auth->id, -$money, 9, $memo = '申请合伙人');
        // Db::name("share_user")->where(['user_id'=>$this->auth->id])->update(['is_union'=>1]);
        $this->success('成功');
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 积分兑换股票
     * qi10.28
     */
    public function scoreStock()
    {
        $score = $this->request->post("score");
        if (!$score) {
            $this->error('缺少必传参数');
        }
        Db::startTrans();
        $re_statue = (new ShareUser)->userScoreLog($this->auth->id, -$score, 8, $memo = '积分兑换股票', true);
        if ($re_statue['status'] == 0) {
            $this->error($re_statue['msg']);
        }
        $stock = $score * 1.2;
        $stock_status = (new ShareUser)->userStockLog($this->auth->id, $stock, 1, $memo = '积分兑换股票', true);
        if ($stock_status['status'] == 0) {
            $this->error($stock_status['msg']);
        }
        $in_status = Db::name("score_stock")->insert(['user_id' => $this->auth->id, 'score' => abs($score), 'stock_v' => abs($stock), 'mobile' => $this->auth->mobile, 'createtime' => time()]);
        if (!$in_status) {
            Db::rollback();
            $this->error('失败');
        }
        Db::commit();
        $this->success('成功');
    }

    /**
     * @return void
     * 返回团队信息
     */
    public function re_user_mobile()
    {
        $user_id = $this->request->post("user_id");


        if (!$user_id) {
            $this->error('缺少必传参数');
        }
        $share_data = Db::name("share_user")->where(['user_id' => $user_id])->find();


        $hai_user = (new ShareUser())->where('role_url', 'like', '%/' . $user_id . '/%')
            ->where('role > 0')
            ->order('role desc')->find();
        if ($hai_user) {
            $role = $hai_user['role'];
        } else {
            $role = $share_data['role'];
        }
        if ($share_data['role'] > $hai_user['role']) {

            $role = $share_data['role'];
        }


        $sh_user = Db::name("share_user")
            ->where('role_url', 'like', '%/' . $user_id . '/%')
            ->select();
        $user_id_arr = array_column($sh_user, 'user_id');
        $user_id_arr = array_merge($user_id_arr, [$user_id]);
        $sh_user_all = Db::name("share_user")
            ->where('user_id', 'in', $user_id_arr)
            ->where(['role' => $role])
            ->select();
        $sh_user_all_arr = array_column($sh_user_all, 'user_id');
        $user_list = [];
        if ($sh_user_all_arr) {
            $user_list = Db::name("user")->where('id', 'in', $sh_user_all_arr)->select();
        }
        $this->success("成功", $user_list);
    }

    /**
     * @return void
     * @throws \think\Exception
     * 团队统计
     */
    public function team_data()
    {
        $user_id = $this->auth->id;
        $row = Db::name("share_user")->where(['user_id' => $user_id])->find();
        //数据统计开始
        $all_nums = Db::name("share_user")
            ->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])
            ->whereOr("user_id", $row['user_id'])
            ->count();//总人数
        //->fetchSql()->select();
        //var_dump($all_nums);die;
        $all_jin = Db::name("share_user")
            ->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])
            ->where("share_user.role", 6)
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->count();//金牌人数
        $all_yin = Db::name("share_user")
            ->where("share_user.role", 5)
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->count();//银牌人数
        $all_xing1 = Db::name("share_user")
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 3)
            ->count();//一星网点
        $all_xing2 = Db::name("share_user")
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 4)
            ->count();//二星网点
        $all_daiyan = Db::name("share_user")
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 2)
            ->count();//代言人
        $all_tuiguang = Db::name("share_user")
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 1)
            ->count();//推广员
        $data_["all_nums"] = $all_nums;//总人数
        $data_["all_jin"] = $all_jin;//金牌人数
        $data_["all_yin"] = $all_yin;//银牌人数
        $data_["all_xing1"] = $all_xing1;//一星网点
        $data_["all_xing2"] = $all_xing2;//二星网点
        $data_["all_daiyan"] = $all_daiyan;//代言人
        $data_["all_tuiguang"] = $all_tuiguang;//推广员
        $this->success("成功", $data_);
    }

    public function setLeader()
    {
        $captcha = $this->request->post("captcha");//短信验证码
        $user_id = $this->auth->id;
        if (!Sms::check($this->auth->mobile, $captcha, 'transferpoints')) {
            $this->error(__('验证码不正确'));
        }
        $user = Db::name("share_user")->where('user_id', $user_id)->find();
        if ($user['role'] < 3) {
            $this->error(__('一星网店经销商以下用户不可设置分隔收益'));
        }
        $in_status = Db::name("leader_user")->where(['user_id' => $user_id])->where('status', 'in', '0,1')->find();
        if ($in_status) {
            $this->success("申请成功");
        }
        $in_status = Db::name("leader_user")->insert(['user_id' => $user_id, 'createtime' => time()]);
        if ($in_status) {
            $this->success("申请成功");
        } else {
            $this->error(__('申请失败'));
        }

    }

    /**
     * 市场团队数据
     */
    public function scTemaData()
    {
        $user_id = $this->auth->id;
        $type = $this->request->post("type");
        $share = Db::name("share_user")->where(['user_id' => $user_id])->find();
        if ($share['is_sep_income'] != 1 && $share['is_leader'] != 1) {
            $this->error('无权访问');
        }
        $data = (new ShareUser())->teamCount($user_id, $type);
        $this->success("成功", $data);
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 独立分割审核
     */
    public function extIncome()
    {
        $user_id = $this->auth->id;
        $id = $this->request->post("id");
        $leader = Db::name("leader_user")->where(['id' => $id, 'status' => 0])->find();
        if (!$leader) {
            $this->error('数据有误');
        }
        $share = Db::name("share_user")->where(['user_id' => $user_id])->find();
        if ($share['is_leader'] != 1 && $share['is_sep_income'] != 1) {
            $this->error('无权审核');
        }
        $data = (new ShareUser())->setSepTeamUser($leader['user_id']);
        if ($data['code'] == 1) {
            Db::name("leader_user")->where(['id' => $id, 'status' => 0])->update(['status' => 1, "set_user_id" => $user_id]);
            $this->success("成功");
        } else {
            $this->error($data['msg']);
        }
    }

    /*
     * 项目负责人申请列表
     */
    public function ListIncome()
    {
        $user_id = $this->auth->id;
        $share_one = Db::name("share_user")->where(['user_id' => $user_id])->find();
        if ($share_one['is_leader'] != 1) {
            $this->error('无权审核');
        }
        $status = $this->request->post("status");
        if ($status == 1) {
            $where["status"] = ['in', '1,2'];
        } else {
            $where["status"] = 0;
        }

        $list = Db::name("leader_user")->where($where)->select();
        $pattern = Db::name("config")->where(['name'=>'pattern'])->value('value');
        if(isset($pattern) && $pattern == 2){
            $dj = ['无', '代言人', '创客', '网店店长', '网店店主', '一级经销商', '二级经销商', '三级经销商'];
        }elseif(isset($pattern) && $pattern == 3){
            $dj = ['无', '推广员', '代言人', '一星网店', '二星网店', '一级代理商', '二级代理商', '三级代理商'];
        }else{
            $dj = ['无', '推广员', '代言人', '一星网店经销商', '二星网店经销商', '银牌经销商', '金牌经销商', '钻石经销商'];
        }
        if ($list) {
            foreach ($list as $k => $v) {
                $share = Db::name("share_user")->where(['user_id' => $v['user_id']])->find();
                $user = Db::name("user")->where(['id' => $v['user_id']])->find();
                if ($share) {
                    $list[$k]['role_name'] = $dj[$share['role']];
                } else {
                    $list[$k]['role_name'] = '';
                }
                $list[$k]['nickname'] = $user['nickname'];
                $list[$k]['mobile'] = $user['mobile'];
            }
        }

        $this->success("成功", $list);
    }

    /*
         * 独立负责人审核列表
         */
    public function ListSepIncome()
    {
        $user_id = $this->auth->id;
        $share_one = Db::name("share_user")->where(['user_id' => $user_id])->find();
        if ($share_one['is_sep_income'] != 1) {
            $this->error('无权审核');
        }
        $status = $this->request->post("status");
        if ($status == 1) {
            $where["status"] = ['in', '1,2'];
            $where["set_user_id"] = $user_id;
            $list = Db::name("leader_user")->where($where)->select();
        } else {
            $where["status"] = 0;
            $flags_list = Db::name("share_user_flags")->where(['user_flags' => $share_one['user_flags']])->select();
            $user_id_arr = array_column($flags_list, 'user_id');
            $list = Db::name("leader_user")->where($where)->where('user_id', 'in', $user_id_arr)->select();
        }

        $pattern = Db::name("config")->where(['name'=>'pattern'])->value('value');
        if(isset($pattern) && $pattern == 2){
            $dj = ['无', '代言人', '创客', '网店店长', '网店店主', '一级经销商', '二级经销商', '三级经销商'];
        }elseif(isset($pattern) && $pattern == 3){
            $dj = ['无', '推广员', '代言人', '一星网店', '二星网店', '一级代理商', '二级代理商', '三级代理商'];
        }else{
            $dj = ['无', '推广员', '代言人', '一星网店经销商', '二星网店经销商', '银牌经销商', '金牌经销商', '钻石经销商'];
        }
        if ($list) {
            foreach ($list as $k => $v) {
                $share = Db::name("share_user")->where(['user_id' => $v['user_id']])->find();
                $user = Db::name("user")->where(['id' => $v['user_id']])->find();
                if ($share) {
                    $list[$k]['role_name'] = $dj[$share['role']];
                } else {
                    $list[$k]['role_name'] = '';
                }
                $list[$k]['nickname'] = $user['nickname'];
                $list[$k]['mobile'] = $user['mobile'];
            }
        }

        $this->success("成功", $list);
    }

    /**
     *创收记录
     */
    public function getAdvertLog()
    {

        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $srart = strtotime($starttime);
        $end = strtotime($endtime);

        $offset = $this->request->post("offset"); // 第几页
        $lists = [];
        $user_money_log = db('user_advert_price_log')->where('user_id', $this->user_id)->field('order_id,id,before,after,money,type,createtime as addtime,memo as type_name')->whereBetween("createtime",[$srart,$end])->select();
        foreach ($user_money_log as $k => $v) {

            if ($v['before'] >= $v['after']) {
                $user_money_log[$k]['money'] = abs($v['money']);
                $user_money_log[$k]['flag'] = '-';
            } else {
                $user_money_log[$k]['flag'] = '+';
            }
            $user_money_log[$k]['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
            switch ($v['type']) {
                case 0:
                    $goods_title = Db::name("shopro_order_item")->where(['order_id'=>$v['order_id']])->value("goods_title");
                    if ($user_money_log[$k]['flag'] == '+') {

                        $user_money_log[$k]['type_name'] = '商品退单-'.$goods_title;
                        break;
                    } else {
                        $user_money_log[$k]['type_name'] = '购买商品-'.$goods_title;
                        break;
                    }
                case 1:
                    if ($user_money_log[$k]['flag'] == '+') {
                        $user_money_log[$k]['type_name'] = '日创收';
                        break;
                    } else {
                        $user_money_log[$k]['type_name'] = '日创收退回';
                        break;
                    }
                case 2:
                    if ($user_money_log[$k]['flag'] == '+') {
                        $user_money_log[$k]['type_name'] = '周创收';
                        break;
                    } else {
                        $user_money_log[$k]['type_name'] = '周创收退回';
                        break;
                    }

                case 3:
                    if ($user_money_log[$k]['flag'] == '+') {
                        $user_money_log[$k]['type_name'] = '提现退回';
                        break;
                    } else {
                        $user_money_log[$k]['type_name'] = '提现';
                        break;
                    }
                case 3:
                    if ($user_money_log[$k]['flag'] == '+') {
                        $user_money_log[$k]['type_name'] = '佣金';
                        break;
                    } else {
                        $user_money_log[$k]['type_name'] = '佣金';
                        break;
                    }
            }
            unset($user_money_log[$k]['before']);
            unset($user_money_log[$k]['after']);
            unset($user_money_log[$k]['type']);
        }
        $lists = array_merge($lists, $user_money_log);
        $last_name = array_column($lists, 'addtime');
        array_multisort($last_name, SORT_DESC, $lists);
        $arr = array_chunk($lists, 10);
        if (count($arr) > $offset || $offset == 1) {
            $this->success('成功', isset($arr[$offset - 1]) ? $arr[$offset - 1] : []);
        }
        $this->success('成功', []);

    }

    public function moneyNew()
    {
        $re_data = [];
        $info = db('notice_user')->where('user_id', $this->auth->id)->where('notice_id', 100000001)->find();
        if (!$info) {
            $re_data['content'] = "亲，近期各分公司陆续正式启动V2.0市场，现把总余额数据迁移到“向未来”栏目里的“老余额”。即日再产生的收益在“新余额”内展示，新余额每日提现2000元以内。";
            $in_data['user_id'] = $this->auth->id;
            $in_data['notice_id'] = 100000001;
            $in_data['createtime'] = time();
            db('notice_user')->insert($in_data);
            $this->success('成功', $re_data);
        } else {
            $this->error();
        }
    }
    /**
     *添加直播间信息
     */
    public function liveAdd(){
        $xin_time = time();
        $live_name = $this->request->post("live_name");
        $live_str_time = $this->request->post("live_str_time");
        if(!$live_str_time || !$live_name){
            $this->error("缺少必传参数");
        }
        $xindata = Db::name("live")->where(['is_live'=>1])->where('xin_time','>',time())->find();
        if($xindata){
            $this->error("有正在直播的");
        }
        $in_data['live_name'] = $live_name;
        $in_data['live_str_time'] = $live_str_time;
        $in_data['user_id'] = $this->auth->id;
        $in_data['create_time'] = time();
        $in_data['xin_time'] = $xin_time + 30;
        $in_data['is_comment'] = 1;
        if (strpos($this->auth->avatar, 'https://') !== false){
            $in_data['avatar'] = $this->auth->avatar;
        }
        $data = Db::name("live")->find();
        if($data){
            $insert_data = Db::name("live")->where(['id'=>$data['id']])->update($in_data);
            if($insert_data){
                $this->success('成功');
            }else{
                $this->error("添加失败");
            }
        }else{
            $insert_data = Db::name("live")->insert($in_data);
            if($insert_data){
                $this->success('成功');
            }else{
                $this->error("添加失败");
            }
        }

    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 直播心跳
     */
    public function liveXin(){
        $xin_time = time();
        $is_comment = $this->request->post("is_comment");
        if($is_comment){
            $in_data['is_comment'] = $is_comment;
        }
        $in_data['xin_time'] = $xin_time + 30;

        $data = Db::name("live")->find();
        if($data){
            $insert_data = Db::name("live")->where(['id'=>$data['id']])->update($in_data);
            if($insert_data){
                $this->success('成功');
            }else{
                $this->error("添加失败");
            }
        }
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function liveOpenClose(){
        $is_live = $this->request->post("is_live");
        if(!$is_live && $is_live != 0){
            $this->error("缺少必传参数");
        }
        $in_data['is_live'] = $is_live;//0未开播1已开播
        $data = Db::name("live")->find();
        if($data){
            $insert_data = Db::name("live")->where(['id'=>$data['id']])->update($in_data);
            if($insert_data !== false){
                $this->success('成功');
            }else{
                $this->error("操作失败");
            }
        }else{
            $this->error("数据有误");
        }
    }
    public function liveComment(){
        $is_comment = $this->request->post("is_comment");
        if(!$is_comment && $is_comment != 0){
            $this->error("缺少必传参数");
        }
        $in_data['is_comment'] = $is_comment;//0未开播1已开播
        $data = Db::name("live")->find();
        if($data){
            $insert_data = Db::name("live")->where(['id'=>$data['id']])->update($in_data);
            if($insert_data !== false){
                $this->success('成功');
            }else{
                $this->error("操作失败");
            }
        }else{
            $this->error("数据有误");
        }
    }
    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取正在直播间信息
     */
    public function liveDate(){
        $data = Db::name("live")->where(['is_live'=>1])->where('xin_time','>',time())->find();
        if($data){
            if(isset($this->auth->id) && $data['user_id'] == $this->auth->id){
                $this->error("是当前直播人");
            }
            $this->success('成功',$data);
        }else{
            $this->error("没有正在开播的");
        }
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 连麦申请
     */
    public function liveEven(){
        $status = $this->request->post("status",0);//0申请连麦5取消3断开
        $xindata = Db::name("live_even")->where('status','in','0,1,4')->count();
        if($xindata >= 4){
            $this->error("无多余的麦位");
        }
        $user_data = Db::name("live_even")->where(['user_id'=>$this->auth->id])->where('status','in','0,1,4')->find();
        if($user_data){
            if($user_data['status'] == 0){
                $this->error("已申请连麦，请耐心等待");
            }elseif ($user_data['status'] == 1){
                $this->error("正在连麦");
            }elseif ($user_data['status'] == 1){
                $this->error("已邀请");
            }
        }
        $in_data['user_id'] = $this->auth->id;
        $in_data['create_time'] = time();
        $in_data['status'] = $status;
        $data = Db::name("live_even")->where(['user_id'=>$this->auth->id])->find();
        if($data){
            $insert_data = Db::name("live_even")->where(['id'=>$data['id']])->update($in_data);
            if($insert_data !== false){
                $this->success('成功',$data);
            }else{
                $this->error("添加失败");
            }
        }else{
            $insert_data = Db::name("live_even")->insert($in_data);
            if($insert_data){
                $data = Db::name("live_even")->where(['user_id'=>$this->auth->id])->find();
                $this->success('成功',$data);
            }else{
                $this->error("添加失败");
            }
        }
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 审核连麦
     */
    public function liveEvenSh(){
        $status = $this->request->post("status");//1同意2拒绝3挂断
        $id = $this->request->post("id");
        if(!$status && $status != 0){
            $this->error("缺少必传参数");
        }
        if(!$id){
            $this->error("缺少必传参数");
        }
        $in_data['status'] = $status;//0未开播1已开播
        $in_data['sh_time'] = time();
        $data = Db::name("live_even")->where(['id'=>$id])->find();
        if($data){
            $insert_data = Db::name("live_even")->where(['id'=>$data['id']])->update($in_data);
            if($insert_data !== false){
                $this->success('成功');
            }else{
                $this->error("操作失败");
            }
        }else{
            $this->error("数据有误");
        }
    }
    public function liveEvenData(){
        $data = Db::name("live_even")->where('status','in','0,1')->select();
        foreach ($data as $k=>$v){
            $user_data = Db::name("user")->where(['id'=>$v['user_id']])->find();
            $data[$k]['username'] = $user_data['username'];
            $data[$k]['avatar'] = $user_data['avatar'];
        }
        $this->success('成功',$data);
    }
}
